带有“ span:contains('string')”的selenium.common

我正在使用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中,它不起作用


慕斯王
浏览 540回答 2
2回答

胡子哥哥

css_selectorSelenium不支持使用按文本定位元素(尽管它可以在开发人员工具控制台中使用)。唯一的可能性是xpathelement = "//span[contains(text(), 'Control panel')]"my_driver.find_element_by_xpath(element)编辑:@FlorentB的评论:css selector控制台也不支持A ,但是JQuery支持它。$('...')控制台中的from是该页面的缩写,document.querySelector通常会被JQuery覆盖。

不负相思意

错误说明了一切: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适用于本机不支持CSS选择器(IE7,IE8等)的浏览器,这会导致浏览器和选择器之间的不一致。因此,更好的解决方案是将<span>标记的其他任何属性都使用如下:element = "span[attribute_name=attribute_value]"替代解决方案您可以根据流行的DOM树使用以下xpath之一:使用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选择器,但JQuery支持它。$('...')控制台中的from是该页面的缩写形式,document.querySelector通常会被覆盖JQuery。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python