xpath - XPath text() returns 2 Values how to combine them to one
问题描述
I have this:
const $x = xp => {
const snapshot = document.evaluate(
xp, document, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
return [...Array(snapshot.snapshotLength)]
.map((_, i) => snapshot.snapshotItem(i))
;
};
console.log($x('//h2/text()[1]'));
console.log($x('//h2/text()[2]'));
<h2 _ngcontent-gbb-c105="" class="text-center">HERZLICH WILLKOMMEN <br _ngcontent-gbb-c105=""> BEI DEINER ANKER APP</h2>
is there a way to get both text()[1]
and text()[2]
joined together so I could do something like this: //*[text()='HERZLICH WILLKOMMEN BEI DEINER ANKER APP']
解决方案
我会简单地选择h2
元素,然后读出它的textContent
属性:
const $x = xp => {
const snapshot = document.evaluate(
xp, document, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
return [...Array(snapshot.snapshotLength)]
.map((_, i) => snapshot.snapshotItem(i))
;
};
console.log($x('//h2')[0].textContent);
<h2 _ngcontent-gbb-c105="" class="text-center">HERZLICH WILLKOMMEN <br _ngcontent-gbb-c105=""> BEI DEINER ANKER APP</h2>
或者您可以使用 XPath 表达式string((//h2)[1])
,但显然您的 JavaScript 代码要使用 XPath API,然后需要更改为使用不同的结果类型:
const text = document.evaluate('string((//h2)[1])', document, null, XPathResult.STRING_TYPE, null).stringValue;
console.log(text);
<h2 _ngcontent-gbb-c105="" class="text-center">HERZLICH WILLKOMMEN <br _ngcontent-gbb-c105=""> BEI DEINER ANKER APP</h2>
推荐阅读
- python - NetworkX 中图形中的平行/重复边数
- python - Python GTK+ 3:是否可以使背景窗口不可见?
- excel - 通过Powershell关闭时无法停止所有excel进程
- php - 从“”获取电子邮件正文中的“”符号,但仍编码为 UTF-8
- git - git 无法暂存文件,将所有文件显示为重复但字符大小写不是问题
- c++ - 如何将 `void(*fn)(const char *, ...)` 转换为 `std::function`,反之亦然
- javascript - 将数据从客户端传递到服务器
- java - 如何比较 2 个文件并删除不存在的行?
- php - Laravel 与枢轴的多态关系
- c# - 获得不同的列表后,在查询中使用结果