我的 HTML 代码由多个 div
组成。每个 div
内都有一个 anchor 标记列表。我需要获取 子容器
div
中 anchor 标记的 href
值和文本值。我正在使用 Selenium 来获取网页的 HTML 代码。
HTML 代码:
<body>
<div id="main-container">
<a href="www.one.com">One</a>
<a href="www.two.com">Two</a>
<a href="www.three.com">Three</a>
<div id="sub-container">
<a href="www.abc.com">Abc</a>
<a href="www.xyz.com">Xyz</a>
<a href="www.pqr.com">Pqr</a>
</div>
</div>
</body>
Java代码:
List<WebElement> list = driver.findElements(By.xpath("//*[@href]"));
for (WebElement element : list) {
String link = element.getAttribute("href");
System.out.println(e.getTagName() + "=" + link);
}
输出:
a=www.one.com
a=www.two.com
a=www.three.com
a=www.abc.com
a=www.xyz.com
a=www.pqr.com
我需要的输出:
a=www.abc.com , Abc
a=www.xyz.com , Xyz
a=www.pqr.com , Pqr
最佳答案
试试这个,
List<WebElement> list = driver.findElements(By.xpath("//div[@id='sub-container']/*[@href]"));
for (WebElement element : list) {
String link = element.getAttribute("href");
System.out.println(element.getTagName() + "=" + link +", "+ element.getText());
}
关于java - 如何在 Java 中使用 Selenium 获取 div 内的 anchor 标记 href 和 anchor 标记文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624536/