You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTMLUnit使用getByXPath批量获取href属性值的问题

解决方案

环境支持XPath 2.0及以上版本(如HtmlUnit 2.40+)

直接使用//@href/string()作为查询语句即可一次性返回所有href属性的字符串值,无需额外调用getValue()方法,代码示例:

WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(siteRef);
List<String> hrefs = page.getByXPath("//@href/string()");

该语法会遍历所有匹配到的href属性节点,逐个转换为字符串值返回。


环境仅支持XPath 1.0

XPath 1.0的string()函数仅能处理单个节点,传入节点集时默认只取第一个节点转换,因此无法通过单条XPath直接返回所有属性的字符串列表,推荐对原查询结果做批量转换即可,示例代码如下:

WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(siteRef);
// 先查询所有DomAttr节点
List<DomAttr> hrefAttrs = page.getByXPath("//@href");
// 批量转换为字符串值
List<String> hrefValues = new ArrayList<>();
for (DomAttr attr : hrefAttrs) {
    hrefValues.add(attr.getValue());
}
// JDK8及以上版本可以用流简化写法
// List<String> hrefValues = hrefAttrs.stream().map(DomAttr::getValue).toList();

补充说明:你之前使用string(//@href)仅返回第一个结果是XPath 1.0的标准特性,属于预期行为。

内容的提问来源于stack exchange,提问作者David S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:18:03