首页 > 解决方案 > 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']

标签: xpath

解决方案


我会简单地选择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>


推荐阅读