您好,我正在使用 HtmlUnit library我需要从 a
中获取一些 href 属性标记,在一些 div 中:
<div class="threadpostedin td alt">
<p>Forum:<br>
<a href="programming/website-development/"
title="Website Development">Website
Development</a></p>
</div>
这个 div 位于 <li>
中它位于 <ol>
内
获取ol
我这样做了:
HtmlOrderedList l = (HtmlOrderedList) this.page.getElementById("searchbits");
html:
<ol class="searchbits" id="searchbits" start="1">
现在从我发布的 div 中,我需要获取 href "programming/website-development/"
,但我不确定该怎么做。是的,div 有一个类名,但如果我这样做的话
for (DomElement ele : l.getChildElements()) {
System.out.println(ele.getByXPath("//div[@class='threadpostedin td alt']").size());
break;
}
它将打印 15,因为 ol
中总共有 15 个列表, 在每个列表中都有一个类为 threadpostedin td alt
的 div .我需要做的是类 threadpostedin td alt
的确切 div在DomElement
我从迭代中得到,但没有得到该类的所有 div 的列表。
有没有办法用 HtmlUnit 做到这一点?
最佳答案
我假设您有多个链接以使其更详细。
HtmlElement element = page.getByXPath("//div[@class='threadpostedin td alt']").get(0);
DomNodeList<DomNode> nodes = element.querySelectorAll("a");
for(DomNode a : nodes) {
if(a.getAttributes().getNamedItem("href") !=null) {
String href = page.getFullyQualifiedUrl(a.getAttributes().getNamedItem("href").getNodeValue()).toString().toLowerCase();
String baseUrl = page.getBaseURL().toString();
}
}
关于java - HtmlUnit 在 DomElement 中按类获取 div 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25096832/