【问题标题】:How to extract the text using Selenium and Java?如何使用 Selenium 和 Java 提取文本?
【发布时间】:2020-06-12 17:56:35
【问题描述】:

getText(), getAttribute("textContent") 没有返回正确的结果。

这是带有标签的html标签:

<span>
class="panel-title text-primary header-font ng-binding" ng-click="titleLink()" style="" xpath="1">Applied Configs: TEST, MSA TEST, MSACONFIGURABLE
</span>

代码试验:

driver.findElement(By.xpath("//*[contains(@name,'Applied Configs')]/div[1]")).getAttribute("textContent"));

driver.findElement(By.xpath("//*[contains(@name,'Applied Configs')]/div[1]")).getText();

返回 Applied Configs: 而不是完整的 Text Applied Configs: TEST, MSA TEST, MSACONFIGURABLE

我不确定我在这里犯了什么错误。

【问题讨论】:

    标签: java selenium xpath gettext getattribute


    【解决方案1】:

    要提取文本Applied Configs: TEST, MSA TEST, MSACONFIGURABLE,因为元素是动态元素,您必须为visibilityOfElementLocated() 诱导WebDriverWait,您可以使用关注Locator Strategies

    • 使用 xpathgetText():

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='panel-title text-primary header-font ng-binding' and starts-with(@ng-click, 'titleLink')]"))).getText());
      
    • 使用 xpathgetAttribute("innerHTML"):

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='panel-title text-primary header-font ng-binding' and starts-with(@ng-click, 'titleLink')]"))).getAttribute("innerHTML"));
      

    更新

    作为替代方案,您可以为TextToBePresentInElementLocated() 诱导 WebDriverWait

    new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//span[@class='panel-title text-primary header-font ng-binding' and starts-with(@ng-click, 'titleLink')][contains(., 'Applied Configs:')]"), ","))
    System.out.println(driver.findElement(By.xpath("//span[@class='panel-title text-primary header-font ng-binding' and starts-with(@ng-click, 'titleLink')][contains(., 'Applied Configs:')]")).getAttribute("innerHTML"));
    

    【讨论】:

    • 你好 Debanjan,我使用了上面提到的代码,但它是第一次打印,因为使用类似的 xpath 我总共有 3 个元素。
    • @SumitDhanawat 是否有任何特定文本,例如TEST 或 innerHTML 中始终预期的其他内容?
    • 应用配置:将始终预期
    • @SumitDhanawat 查看更新后的答案并告诉我状态。
    • 得到timedoutException并且无法理解第二行代码。
    猜你喜欢
    • 2020-01-25
    • 2020-01-01
    • 1970-01-01
    • 2021-12-29
    • 2020-04-13
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多