【问题标题】:How to locate element using text() facing exception(selenium+python)?如何使用面对异常(selenium + python)的文本()定位元素?
【发布时间】:2020-04-04 06:49:33
【问题描述】:

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')]"

【问题讨论】:

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

标签: python selenium selenium-webdriver xpath css-selectors


【解决方案1】:

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

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

希望对你有帮助

【讨论】:

    【解决方案2】:

    您将Xpath 提供给css 选择器,这是错误的!

    您需要将xpath 赋予xpath 函数而不是css selector 函数

    这就是你得到这个错误的原因

    试试这个:

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

    【讨论】:

      【解决方案3】:

      此错误消息...

      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')]"
      

      ...表示您使用的 css 选择器表达式 不是有效的 css 选择器


      Selenium 尚不支持使用 通过文本 定位元素(尽管它可能在开发人员工具控制台中工作)。唯一的可能是

      您可以在selenium.common.exceptions.InvalidSelectorException with "span:contains('string')"找到详细讨论


      因此,根据您提供的 HTML 使用 css_selectors,您可以使用以下 Locator Strategy

      span.menu-text
      

      不过,您的代码试验非常类似于 xpath。所以你需要将find_element_by_css_selector 更改为find_element_by_xpath。如此有效,代码行将是:

      driver.find_element_by_xpath("//span[text()='Download App']")
      

      作为替代,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-19
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多