java - 使用 Selenium 验证 <div> 之间的文本

标签 java selenium webdriver selenium-chromedriver

我需要验证网页上的特定插槽是否已加载。我在 main() 中使用 Selenium WebDriver函数(我应该使用 JUnit 测试用例吗?)。

有什么方法可以检索任何 <div> 之间的文本?有特定的 ID?

如果给出this page :

<div id="center-2" class="promo">
    <div class="unified_widget rcmBody">
        <span class="logo"><img src="someimage.gif" /></span>
        <span class="headline">Make money by Selling items on Amazon</span>
        <span class="link"><a href="/content/sell-on-amazon.htm">Selling On Amazon</a></span>
        <span class="body">Sell your items on Amazon.com. Amazon can help you grow your business and reach more customers.</span>
        <div class="h_rule"></div>
    </div>
</div>

<div id = center-2>给出了,我需要提取

“通过在亚马逊上销售商品赚钱”,
“在亚马逊上销售”,
“在 Amazon.com 上销售您的商品。亚马逊可以帮助您发展业务并吸引更多客户。”

我应该使用哪种方法?

最佳答案

要确保元素已加载,请使用 Implicit and Explicit waits .

通常,当您需要与元素交互时,隐式等待就足够了。一旦设置好,它就会用于每个元素查找。根据我的经验,这足以应对 95% 的情况。

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

如果您需要更高级的等待(或只使用等待一次),显式等待就在您身边。


我知道三种常用的方法来检索具有特定 id 的元素:

  1. 首选方式:

    driver.findElement(By.id("elemId"));
    
  2. 如果您需要从一个元素开始然后搜索其后代,这是一个好方法:

    driver.findElement(By.cssSelector("#elemId"));
    driver.findElement(By.xpath("id('elemId')"));
    
  3. 许多人使用的方式,因为他们熟悉 XPath:

    driver.findElement(By.xpath("//*[@id='elemId']"));
    

了解更多 CSS selectorsXPath ,请参阅网络上的任何教程。


关于文本:

String text = driver.findElement(By.id("center-2")).getText();
System.out.println(text);

输出

Make money by Selling items on Amazon Selling On Amazon Sell your items on Amazon.com. Amazon can help you grow your business and reach more customers.

如果你想独立获得这三个东西,使用例如:

String headline = driver.findElement(By.cssSelector("#center-2 .headline")).getText();
System.out.println(headline);

String link = driver.findElement(By.cssSelector("#center-2 .link")).getText();
System.out.println(link);

String body = driver.findElement(By.cssSelector("#center-2 .body")).getText();
System.out.println(body);

关于java - 使用 Selenium 验证 <div> 之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11543010/

相关文章:

java - 如何在Java中的表的列中添加复选框

Java Sound API - 区分多个相等的USB声卡

java - 如何在返回 void 并引发异常的方法上执行 doThrow 或 thenThrow

python - 对 Selenium 使用随机 userAgent(python)

java - Webdriver - 与远程浏览器通信时出错

java - Webdriver 服务器日志

java - 协变返回类型最佳实践

java - 需要 Selenium 框架通用功能来实现下一个元素的可见性

javascript - selenium.common.exceptions.WebDriverException : Message: unknown error: 'script' must be a string while using execute_script() through Selenium Python

java - Selenium Webdriver - 从 li/a 查找动态 id