selenium – Failed to execute ‘evaluate’ on ‘Document’: The string is not a valid XPath expression

This error message…

SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//span[contains(@class, 'md_countryName_fdxiah8' and text(), 'Colombia')]' is not a valid XPath expression.

…implies that the XPath which you have used was not a valid XPath expression.

Seems you were pretty close. You can use either of the following Locator Strategies:

  • Using xpath 1:

    country = countries.find_element_by_xpath("//span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']")
    
  • Using xpath 2:

    country = countries.find_element_by_xpath("//span[contains(@class, 'md_countryName_fdxiah8') and contains(., 'Colombia')]")
    

Here you can find a relevant discussion on SyntaxError: Failed to execute ‘evaluate’ on ‘Document’: The string ‘//img[contains(‘1236548597′)]’ is not a valid XPath expression


Update

To overcome the element not visible error you need to induce WebDriverWait for visibility_of_element_located() and you can use either of the following Locator Strategy:

element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']")))

Leave a Comment