我试图仅从hrefs属性的xpath查询中获取值,但我不知道如何声明该查询,充其量我在需要使用getValue()获取实际链接的DomAttr列表中获取ref。
我非常简单的设置如下:
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(siteRef);
var hrefs = page.getByXPath("//@href"); // Returns a list of DomAttr
E:这会返回值,但也只会返回找到的第一个元素
var hrefs = page.getByXPath("string(//@href)");
发布于 2021-08-27 07:36:27
我想你是对的,没有办法从String
值中获得getByXPath
的数组(或List
)。
不过,您可以通过利用java streams来实现这一行为。在这里,您可以从使用该结果列表的其他可能性中受益(例如,对其进行过滤或使用其他处理,如String
上的toLowerCase
):
var hrefs = page.getByXPath("//@href")
.stream()
.filter(o -> o instanceof DomAttr) //to be sure you have the correct type
.map(o -> ((DomAttr) o)) //cast the stream from Object to DomAttr
.map(DomAttr::getValue) //get value of every DomAttr
.collect(Collectors.toList()); //collect it to a list
hrefs
现在包含一个List<String>
。
您可以进一步处理流,而不是在最后一步中对结果进行collect
。
https://stackoverflow.com/questions/68948709
复制相似问题