HTMlUnit - getByXPath - 从属性列表取回值
HTMlUnit - getByXPath - Get Values Back From Attribute List
我正在尝试从 hrefs 属性的 xpath 查询中获取值,但我不知道如何陈述查询,充其量我将我的引用返回到我需要的 DomAttr 列表中使用 getValue() on 获取实际的 link.
我非常简单的设置如下:
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(siteRef);
var hrefs = page.getByXPath("//@href"); // Returns a list of DomAttr
E:这个 returns 值,但它也只是 returns 它找到的第一个元素
var hrefs = page.getByXPath("string(//@href)");
我想你是对的,无法从 getByXPath
值中获取 String
的数组(或 List
)。
不过,您可以通过使用 java 流来实现该行为。在那里,您可以从使用该结果列表的其他可能性中受益(例如过滤它或使用其他处理,例如 String
s 上的 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
计算结果。
我正在尝试从 hrefs 属性的 xpath 查询中获取值,但我不知道如何陈述查询,充其量我将我的引用返回到我需要的 DomAttr 列表中使用 getValue() on 获取实际的 link.
我非常简单的设置如下:
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(siteRef);
var hrefs = page.getByXPath("//@href"); // Returns a list of DomAttr
E:这个 returns 值,但它也只是 returns 它找到的第一个元素
var hrefs = page.getByXPath("string(//@href)");
我想你是对的,无法从 getByXPath
值中获取 String
的数组(或 List
)。
不过,您可以通过使用 java 流来实现该行为。在那里,您可以从使用该结果列表的其他可能性中受益(例如过滤它或使用其他处理,例如 String
s 上的 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
计算结果。