【问题标题】:How to locate a span with a specific text in Selenium? (Using Java)如何在 Selenium 中找到具有特定文本的跨度? (使用 Java)
【发布时间】:2016-11-26 19:37:17
【问题描述】:

我无法使用 java 在 Selenium 中定位 span 元素。

HTML 看起来像:

<div class="settings-padding">
<span>Settings</span>
</div>

我尝试了以下方法,但没有成功:

By.xpath("span[.='Settings']")

By.xpath("span[text()='Settings']")

By.cssSelector("div[class='settings-padding']"))

以及其他一些类似的尝试。你能给我指出最好的方法吗?就目前而言,我在 Eclipse 中经常收到“无法定位元素”错误。

【问题讨论】:

    标签: java selenium xpath selenium-webdriver


    【解决方案1】:

    您所有的xpath 看起来都还可以,只是一些syntactically 不正确。你在xpath 中缺少//

    正确的xpath如下:-

    By by = By.xpath("//span[.='Settings']")
    

    或者

    By by = By.xpath("//span[text()='Settings']")
    

    或者

    By by = By.xpath("//div[@class='settings-padding']/span"))
    

    或者你可以使用cssSelector :-

    By by = By.cssSelector("div.settings-padding > span"))
    

    使用上述任何一个通过定位器,您可以定位元素如下:-

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement el = wait.until(presenceOfElementLocated(by));
    

    希望对您有所帮助...:)

    【讨论】:

      【解决方案2】:

      对于下面的元素

      <span class="test-button__text">
          Test Text
      </span>
      

      以下解决方案适用于我

      driver.find_element_by_xpath("//span[contains(@class, 'test-button__text') and text()='Test Text']")
      

      【讨论】:

        猜你喜欢
        • 2016-01-18
        • 2019-03-23
        • 2021-09-14
        • 1970-01-01
        • 2022-01-10
        • 2018-11-11
        • 2021-10-10
        • 1970-01-01
        • 2021-06-01
        相关资源
        最近更新 更多