【问题标题】:NodeJS - how to scrape ld+json data and save it to an objectNodeJS - 如何抓取 ld+json 数据并将其保存到对象
【发布时间】:2021-01-31 17:05:48
【问题描述】:

我一直在尝试找到一种方法来获取应用程序/ld+json 内容并将其保存到本地对象。我想要的是将它保存到一个对象中,并且在我的程序中,我将能够 console.log(data.offers.availability) 这将导致日志记录:“InStock”,以及每个数据值。

我目前有这个:

            let content = JSON.stringify($("script[type='application/ld+json']").html())
            let filteredJson = content.replace(/\\n/g, '')
            let results = JSON.parse(filteredJson)
            console.log(results)

这会导致:- 不允许我使用 console.log(results.offers.availability)

 {    "@context": "http://schema.org/", 
   "@type": "Product",    "name": "Apex Legends - Bangalore - Mini Epics",
    "description": "<div class="textblock"><p><h2>Apex Legends - Bangalore - Mini Epics </h2><p>Helden uit alle uithoeken van de wereld strijden voor eer, roem en fortuin in Apex Legends. Weta Workshop betreedt the Wild Frontier en brengt Bangalore met zich mee - Mini Epics style!</p><p>Verzamel alle Apex Legends Mini Epics en voeg ook Bloodhound en Mirage toe aan je collectie!</p></p></div>",
"brand": {
        "@type": "Thing",
        "name": "Game Mania"    
},
"aggregateRating": {        
        "@type": "AggregateRating",
        "ratingValue": "5",
        "ratingCount": "2"    
},
"offers": {        
        "@type": "Offer",
        "priceCurrency": "EUR",
        "price": "19.98",        
        "availability" : "InStock"    
   }
}

我正在尝试抓取和保存的数据:

【问题讨论】:

  • 呃,不要用JSON.stringify?此外,我会推荐 .text() 而不是 .html() 以获得没有转义的实体。
  • @Bergi:有趣的是,当我将.text() 与我的示例代码一起使用时,我得到了SyntaxError: Unexpected end of JSON input,它与.html() 一起使用,或者我这样做的方式。 .text() 似乎返回一个空字符串。
  • @eol 您在节点中使用什么 DOM 实现,$ 是什么?我记得一些浏览器没有脚本的文本内容的问题。但不管怎样,.html().text() 都返回字符串,而JSON.stringify() 是错误的。要删除换行符,请替换 /\n/g 而不是 /\\n/g
  • 我正在使用cheerio。经过一些调试,我发现了以下行:github.com/cheeriojs/cheerio/blob/main/lib/static.js#L102。据此,如果当前元素的 tagName 为script,则它们不会下降/递归,因此将返回一个空字符串。

标签: javascript node.js json ld


【解决方案1】:

正如Bergi 指出的那样,问题在于您在已经是字符串的内容上使用JSON.stringify,但出于好奇,我自己尝试了这个。考虑以下测试:

index.html(通过 localhost:4000 提供):

<html>
<script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "Product",
        "name": "Apex Legends - Bangalore - Mini Epics",
        "offers": {
            "@type": "Offer",
            "priceCurrency": "EUR",
            "price": "19.98",
            "availability": "InStock"
        }
    }
</script>
<body>
<h2>Index</h2>
</body>
</html>

NodeJS 脚本:

const superagent = require('superagent');
const cheerio = require('cheerio');

(async () => {
    const response = await superagent("http://localhost:4000");

    const $ = cheerio.load(response.text);
    // note that I'm not using .html(), although it works for me either way
    const jsonRaw = $("script[type='application/ld+json']")[0].children[0].data; 
    // do not use JSON.stringify on the jsonRaw content, as it's already a string
    const result = JSON.parse(jsonRaw);
    console.log(result.offers.availability);
})()

result 现在是一个对象,它保存来自脚本标签和日志的数据result.offers.availability,将按预期打印InStock

【讨论】:

  • 嘿!非常感谢您花时间帮助我。这适用于也使用 application/ld+json 的其他站点。然而,在这个网站(问题基于)它得到一个错误(未定义:5),纯粹是因为描述内容太长并且其中有空格。通过添加“jsonRaw2 = jsonRaw.replace(/\n/g, '')”然后解析 jsonRaw2 很容易解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 2018-05-03
相关资源
最近更新 更多