python - Selenium 蟒 : find_element_by_css_selector() using :contains()

标签 python xpath selenium css-selectors

在 Python 上的 Selenium 中,我尝试使用

选择一个元素
driver = webdriver.Firefox()
driver.find_element_by_css_selector("td:contains('hello world')")

这给了我错误:

>>>> selenium.common.exceptions.WebDriverException: Message: u'An invalid or illegal string was specified' 

我可以通过这种方式使用许多不同的 CSS 选择器来选择元素,但是使用 :contains() 似乎总是会引发错误。注意:当我尝试使用时出现同样的错误:

driver.find_element_by_xpath("//td[contains(text(),'hello world')]")

请指教。谢谢!

编辑:已解决!

问题解决了!非常感谢你的帮助!我犯了两个重大错误: 1.) 我认为 :contains() 是一个被接受的 css3 选择器(事实证明它不是当前规范的一部分,这就是为什么我不能那样选择) 2.) xpath 选择器会很好,除非我使用的解析器假定 xpath 中永远不会有任何空格,所以它用空格分隔参数。因此,当我传入 xpath 选择器时

//td[contains(text(),'hello world']

解析器在“hello”之后的空格处将其截断,因此 xpath 选择器看起来像

//td[contains(text(),'hello

这显然会引发错误。所以我需要调整我的解析以正确读取我的 xpath 选择器。

再次感谢您所有快速、有用的回答!

最佳答案

find_element_by_xpath_selector 替换为 find_element_by_xpath (没有 find_element_by_xpath_selector 方法):

driver = webdriver.Firefox()
...
driver = driver.find_element_by_xpath(u"//td[contains(text(), 'hello')]")

完整示例

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://python.org')
link = driver.find_element_by_xpath(u'//a[contains(text(), "Download")]')
link.click()

关于python - Selenium 蟒 : find_element_by_css_selector() using :contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18491358/

相关文章:

internet-explorer - Internet Explorer 中的 DOM 级别 3 XPath

selenium - 如何自动化语音应用程序测试

python - 如何使用 python 选择 selenium 中的最后一个下拉选项?

javascript - Scrapy 中的 Selenium + PhantomJS

xml - XPath中的逻辑或?为什么不加工?

python - "Can' t 初始化字符集utf8mb4"with Windows mysql-python

python - 使用 beautiful soup 和 python 解析 HTML : working with table data

python - 引用列表中的元素

xml - 获取列表中每个元素的子字符串,并使它们在XSLT中与众不同

python - numpy.polyval() 的反函数