首页 > 解决方案 > 如何使用面对异常(selenium + python)的文本()定位元素?

问题描述

HTML

<span class="menu-text">Download App</span>

我的代码来定位元素

driver.find_element_by_css_selector("//span[contains(text(),'App')]")

或者

driver.find_element_by_css_selector("//span[contains(.,'App')]")

当我运行它时,报告了一个异常:

selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "//span[contains(text(),'App')]" is invalid: InvalidSelectorError: '//span[contains(text(),'App')]' is not a valid selector: "//span[contains(text(),'App')]"

标签: pythonseleniumselenium-webdriverxpathcss-selectors

解决方案


由于您使用 xpath 表达式,请driver.find_element_by_xpath改用

driver.find_element_by_xpath("//span[contains(text(),'App')]")

希望这可以帮助


推荐阅读