selenium - Failed to execute 'evaluate' on 'Document': The string is not a valid XPath expression

There is the following page.

http://remitly.com/us/en/

When you click on a select, a list with countries appears. I try to select one country, for example, Colombia and click on it. But I get an error.

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

select = driver.find_element_by_class_name('f1wrnyr7')
select.click()
countries = driver.find_element_by_class_name('f1o6pohl')
country = countries.find_element_by_xpath("//span[contains(@class, 'md_countryName_fdxiah8' and text(), 'Colombia')]")

Solution 1:

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']")))

Solution 2:

perhaps you were trying something like this (change xpaths as follows, based on your needs):

notice here that the text node should be equal to 'Colombia': //span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']

or, the text node might contain some long text, but should also contain 'Colombia' in that text:

//span[contains(@class, 'md_countryName_fdxiah8') and contains(text(), 'Colombia')]