selenium.common.exceptions.InvalidSelectorException with “span:contains('string')" [英] selenium.common.exceptions.InvalidSelectorException with "span:contains('string')"
问题描述
我正在 Firefox 中研究 selenium python.我正在尝试通过 css 选择器查找元素
I am working on selenium python in firefox. I am trying to find element by css selector
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 中它不起作用
In selenium IDE I am successfully able to find element by this field but in Python it is not working
推荐答案
Selenium 不支持使用 css_selector
通过文本定位元素(尽管它可以在开发者工具控制台中使用).唯一的可能是 xpath
Using css_selector
to locate element by text is not supported in Selenium (although it will work in the developer tools console). The only possibility is xpath
element = "//span[contains(text(), 'Control panel')]"
my_driver.find_element_by_xpath(element)
@FlorentB 的评论:
a comment by @FlorentB:
控制台也不支持 css 选择器
,但 JQuery 支持.控制台中的 $('...')
是 document.querySelector
的简写,当页面有它时,它通常会被 JQuery 覆盖.
A
css selector
is not supported by the console either, but JQuery supports it. The$('...')
from the console is a shorthand fordocument.querySelector
which is generally overridden with JQuery when the page has it.
这篇关于selenium.common.exceptions.InvalidSelectorException with “span:contains('string')"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!