python - selenium.common.exceptions.InvalidSelectorException 与 "span:contains(' 字符串')”

标签 python css selenium exception css-selectors

我正在 firefox 中开发 selenium python。我正在尝试通过 css 选择器查找元素

element = "span:contains('Control panel')"
my_driver.find_element_by_css_selector(element)

我遇到了错误

 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('Control panel')" is invalid: InvalidSelectorError: 'span:contains('Control panel')' is not a valid selector: "span:contains('Control panel')"

在 selenium IDE 中,我可以通过该字段成功找到元素,但在 Python 中它不起作用

最佳答案

错误说明了一切:

selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "span:contains('Control panel')" is invalid: InvalidSelectorError: 'span:contains('Control panel')' is not a valid selector: "span:contains('Control panel')"

根据 Issue#987 Issue#1547 :

The :contains pseudo-class isn't in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver).

伪类特定于 Sizzle Selector Engine Selenium 1.0依靠。但是,决定 WebDriver 不会支持 Sizzle 风格CSS selectorsSelenium 1.0用过。

现在,一个有趣的事实是:contains pseudo-class 适用于 native 不支持 CSS 选择器(IE7、IE8 等)的浏览器,这会导致 浏览器和选择器之间的不一致。

因此,更好的解决方案是使用 <span> 的任何其他属性标记如下:

element = "span[attribute_name=attribute_value]"

替代方案

您可以根据现行的 DOM Tree 使用以下任一 xpaths :

  • 使用 text() :

    element = my_driver.find_element_by_xpath("//span[text()='Control panel']")
    
  • 使用 contains() :

    element = my_driver.find_element_by_xpath("//span[contains(.,'Control panel')]")
    
  • 使用 normalize-space() :

    element = my_driver.find_element_by_xpath("//span[normalize-space()='Control panel']")
    

使用 jQuery

您还可以按如下方式使用 jQuery:

$('span:contains("Control panel")')

琐事:

来自@FlorentB 的宝贵评论。

CSS selector is not supported by the console either, but JQuery supports it. The $('...') from the console is a shorthand for document.querySelector which is generally overridden with JQuery when the page has it.

关于python - selenium.common.exceptions.InvalidSelectorException 与 "span:contains(' 字符串')”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47883572/

相关文章:

python - Tkinter 图形用户界面 : Update choices of an option menu depending on a choice from another option menu

css - 试图将 2 个响应表置于页面中心

python - 返回子类实例的父方法

javascript - Three-JS - 全屏更改渲染器的大小

javascript - 在响应式容器中重叠图像(object-fit 或 bgimage)

python - selenium.common.exceptions.WebDriverException : Message: unknown error: Chrome failed to start: exited abnormally with ChromeDriver Chrome and Selenium

Selenium IDE : Click on a particular item by name (not the XPath)

javascriptexecutor - 无法单击正文样式标记为 "overflow:hidden"的元素

python - 为什么变量在 BGE Python 中不是全局的

javascript - 使用Socket IO和aiohttp进行Node JS和Python之间的数据传输