0

我有一个这样的 HTML 数据。

<script type="application/ld+json">{ "name": "apple", "price": 100 }</script>
<script type="application/ld+json">{ "name": "banana", "price": 200 }</script>
<script type="application/ld+json">{ "name": "orange", "price": 300 }</script>

如何使用 Xpath 抓取包含“香蕉”的 Json 数据。

例如,下面的 javascript 代码可以抓取包含香蕉的 JSON。但它只是抓取第二个 JSON。

    const htmlString = res;
    const doc = new DOMParser();
    const string = doc.parseFromString(htmlString, 'text/html');
    const result = string.evaluate('//script[@type="application/ld+json"]', string, null, 6, null);
    const character = result.snapshotItem(2);
    console.log(character);

在下面的代码中,变量为 Null。

    const htmlString = res;
    const doc = new DOMParser();
    const string = doc.parseFromString(htmlString, 'text/html');
    const result = string.evaluate('//script[contains(text(), "banana")]', string, null, 6, null);
    const character = result.snapshotItem(1);
    console.log(character);

目标的图像是 { "name": "banana", "price": 200 } 。

4

3 回答 3

1

The index should be 0, since you are targeting exactly which one you want.

const character = result.snapshotItem(0);
于 2021-08-26T14:31:47.113 回答
1

为什么选择 xpath?

const obj = [...document.querySelectorAll("script[type='application/ld+json']")]
  .map(script => JSON.parse(script.textContent))
  .filter((item)=>item.name==="banana")
  
console.log(obj[0])
<script type="application/ld+json">{ "name": "apple", "price": 100 }</script>
<script type="application/ld+json">{ "name": "banana", "price": 200 }</script>
<script type="application/ld+json">{ "name": "orange", "price": 300 }</script>

于 2021-08-26T14:32:49.940 回答
0

您还可以通过以下方式到达:

result = string.evaluate('//script[contains(text(), "banana")]/text()', string, null, 6, null),
character = result.snapshotItem(0).nodeValue;
console.log(character);
于 2021-08-26T15:05:01.507 回答