我有一个像这样的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抓取包含"banana“的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 }。
发布于 2021-08-26 14:31:47
索引应该是0,因为您的目标正是您想要的索引。
const character = result.snapshotItem(0);发布于 2021-08-26 14:32:50
为什么选择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-26 15:05:02
您还可以通过以下方式达到此目的:
result = string.evaluate('//script[contains(text(), "banana")]/text()', string, null, 6, null),
character = result.snapshotItem(0).nodeValue;
console.log(character);https://stackoverflow.com/questions/68940323
复制相似问题