selenium - 无法在 'Document' 上执行 'evaluate':该字符串不是有效的 XPath 表达式

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

有如下页面。

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

当您点击 select 时,会出现一个国家列表。我尝试 select 一个国家,例如哥伦比亚,然后点击它。但是我得到一个错误。

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

也许您正在尝试这样的事情(根据您的需要按如下方式更改 xpath):

注意这里的文本节点应该等于'Colombia': //span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']

或者,文本节点可能包含一些长文本,但该文本中还应包含 'Colombia':

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

您似乎忘记在页面上附加 link。无论如何,XPath 表达式无效,更正后的版本可能是:

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

您可以使用以下 XML 进行测试:

<span class="md_countryName_fdxiah8">Colombia</span>

结果:

Element='<span class="md_countryName_fdxiah8">Colombia</span>'

这个错误信息...

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

...表示您使用的 XPath 不是有效的 XPath 表达式。

看来你很接近。您可以使用以下任一项 :

  • 使用 xpath 1:

    country = countries.find_element_by_xpath("//span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']")
    
  • 使用 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


更新

要克服 元素不可见 错误,您需要为 visibility_of_element_located() 引入 WebDriverWait 并且您可以使用以下定位器策略

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

根据我的经验,Select 元素最好用 Select 函数对象处理。然后每个列表contnet都可以通过它的文本来寻址

您应该导入:

from selenium.webdriver.support.ui import Select

然后

select = Select(driver.find_element_by_class_name('f1wrnyr7'))
select.select_by_visible_text('Colombia')