【问题标题】:Unable to get text from div when text includes <span>文本包含 <span> 时无法从 div 获取文本
【发布时间】:2018-01-15 19:12:56
【问题描述】:

我在 Java 中使用 Selenium。我无法从 span 标签中获取文本,每次都返回一个空字符串。 HTML 代码:

<div class="fade-repeat-animation alert ng-isolate-scope alert-error" ng-class="type && "alert-" + type" ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">
    <button class="close" ng-click="close()" type="button" ng-show="closeable">×</button>
    <div ng-transclude="">
        <span class="ng-scope ng-binding">This text</span>
    </div>
</div>

这是 Selenium 代码:​​

String ipError = within(secs(10)).div(By.xpath("//div[@class='fade-repeat-animation alert ng-isolate-scope alert-error']/div/span")).getAttribute("innerHTML");

我也尝试使用getText()getAttribute("textContent"),但总是返回空String

【问题讨论】:

    标签: java html selenium xpath


    【解决方案1】:

    你必须尝试getText()方法,试试这个代码

    String Spantext=driver.findElement(By.xpath("//span[@class='ng-scope ng-binding']")).getText();
    System.out.println(Spantext);
    

    【讨论】:

    • 非常感谢。这段代码真的帮助了我!一切正常)
    【解决方案2】:

    可能是因为 angularJS Webdriver 无法从 UI 读取文本。 尝试使用此代码,让我知道它是否有效。

    driver.findElement(By.cssSelector(".fade-repeat-animation.alert.ng-isolate-scope .alert-error")).getText();
    

    【讨论】:

    • 不幸的是没有帮助。 "引起:org.openqa.selenium.NoSuchElementException"
    【解决方案3】:

    根据您提供的HTML 打印文本This text,您可以使用以下代码行:

    System.out.println(new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='fade-repeat-animation alert ng-isolate-scope alert-error']//div/span[@class='ng-scope ng-binding']"))).getAttribute("innerHTML"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 2019-09-04
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      相关资源
      最近更新 更多