Skip to main content
 首页 » 编程设计

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

2025年05月04日22lexus

我正在 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 selectors那Selenium 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.