【问题标题】:Cannot get the text of an element. Tried getText() and getAttribute("innerHTML")无法获取元素的文本。试过 getText() 和 getAttribute("innerHTML")
【发布时间】:2019-10-05 11:40:00
【问题描述】:

我试图使用 getText() 和 getAttribute("innerHTML") 获取锚链接的文本,但无法获取文本。这是 HTML:

<tr _ngcontent-c6="">
    <td _ngcontent-c6="" class="text-center0" style="padding-left:25px">ParentText</td>
</tr>
<tr _ngcontent-c6="">
    <td _ngcontent-c6="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
    <td _ngcontent-c6="" class="text-center4" style="text-align: center; color: rgb(111, 156, 7);">
    <a _ngcontent-c6="">$10,000.00</a>
</td>

我尝试了以下 XPath:

.//*[contains(text(),'ParentText')]/../following-sibling::tr/td[2]/a

我试过的代码:

WebElement childText = driver.findElement(By.xpath(".//*[contains(text(),'ParentText')]/../following-sibling::tr/td[2]/a"));

WebDriverWait wait = new WebDriverWait(driver,20);

wait.until(ExpectedConditions.elementToBeClickable(childText));

PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println("Currency Selected:" +childText.getText());

也尝试了最后一行

out.println("Currency Selected:" +childText.getAttribute("innerHTML"));

还尝试了通常的打印。

System.out.println("Currency is : " +childText.getText());

System.out.println("Currency is : " +childText.getAttribute("innerHTML"));

我既没有收到任何错误,也没有收到任何文本输出。 为元素上的 isDisplayed() 传递了一个断言。

    Assert.assertTrue(ChildText.isDisplayed());

【问题讨论】:

    标签: selenium selenium-webdriver webdriver


    【解决方案1】:

    试试textContent

    System.out.println("Currency is : " +childText.getAttribute("textContent"));
    

    【讨论】:

    • 感谢您的知识。像魅力一样工作。你能推荐一个我可以了解这些事情的资源吗?
    • 你可以参考Java doc,我一般会尝试了解当我点击.时每种方法会做什么。并将check always the xpath is correct 在浏览器中使用,然后再在脚本中使用。您还可以在浏览器控制台中验证输出。在使用控制台时得到了textContent 的想法。
    • 在脚本中实现 XPath 之前,我总是使用控制台部分。
    • 兄弟,当我编写脚本时,有时它执行得很好。但有时即使脚本中没有任何修改,也会发生 TimeOutExceptions。你有这样的问题吗?
    • 查看您的其他帖子。
    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多