gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com