如何使用 text() 定位元素面临异常(selenium+python)?

elf*_*elf 3 python selenium xpath css-selectors selenium-webdriver

HTML

<span class="menu-text">Download App</span>
Run Code Online (Sandbox Code Playgroud)

我的代码来定位元素

driver.find_element_by_css_selector("//span[contains(text(),'App')]")
Run Code Online (Sandbox Code Playgroud)

或者

driver.find_element_by_css_selector("//span[contains(.,'App')]")
Run Code Online (Sandbox Code Playgroud)

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

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')]"
Run Code Online (Sandbox Code Playgroud)

Mel*_*lan 6

由于您使用的是 xpath 表达式,因此请driver.find_element_by_xpath改用

driver.find_element_by_xpath("//span[contains(text(),'App')]")
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助