首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Xpath抓取Javascript中包含特定字符串的JSON

如何用Xpath抓取Javascript中包含特定字符串的JSON
EN

Stack Overflow用户
提问于 2021-08-26 14:20:36
回答 3查看 64关注 0票数 0

我有一个像这样的HTML数据。

代码语言:javascript
复制
<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抓取包含"banana“的Json数据。

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

代码语言:javascript
复制
    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。

代码语言:javascript
复制
    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 }。

EN

回答 3

Stack Overflow用户

发布于 2021-08-26 14:31:47

索引应该是0,因为您的目标正是您想要的索引。

代码语言:javascript
复制
const character = result.snapshotItem(0);
票数 1
EN

Stack Overflow用户

发布于 2021-08-26 14:32:50

为什么选择xpath?

代码语言:javascript
复制
const obj = [...document.querySelectorAll("script[type='application/ld+json']")]
  .map(script => JSON.parse(script.textContent))
  .filter((item)=>item.name==="banana")
  
console.log(obj[0])
代码语言:javascript
复制
<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>

票数 1
EN

Stack Overflow用户

发布于 2021-08-26 15:05:02

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

代码语言:javascript
复制
result = string.evaluate('//script[contains(text(), "banana")]/text()', string, null, 6, null),
character = result.snapshotItem(0).nodeValue;
console.log(character);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68940323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档