在 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/