我有一个这样的 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 } 。