我需要验证网页上的特定插槽是否已加载。我在 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
的元素:
首选方式:
driver.findElement(By.id("elemId"));
如果您需要从一个元素开始然后搜索其后代,这是一个好方法:
driver.findElement(By.cssSelector("#elemId")); driver.findElement(By.xpath("id('elemId')"));
许多人使用的方式,因为他们熟悉 XPath:
driver.findElement(By.xpath("//*[@id='elemId']"));
了解更多 CSS selectors和 XPath ,请参阅网络上的任何教程。
关于文本:
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/