英文:
Scrape data from script tag by cheerio
问题
我如何从这样的字符串中提取数据
<script type="application/json" class="js-react-on-rails-component" data-component-name="ItemPriceHeading">
{
"price":"29.0",
"discountedPrice":null,
"offerPrice":null,
"totalPrice":"29.0",
"currency":"PLN"
}
</script>
我需要提取"price"和"currency"的值,但我不知道如何做。
我可以提取所有字符串,但如何提取仅选择的参数?
英文:
How can I scrape data from string like this
<script type="application/json" class="js-react-on-rails-component" data-component-name="ItemPriceHeading">
{
"price":"29.0",
"discountedPrice":null,
"offerPrice":null,
"totalPrice":"29.0",
"currency":"PLN"
}
</script>
I need to scrape "price" and "currency" values, but I can't understand how to do it.
I can scrape all strings, but how do I extract only selected parameters?
答案1
得分: 1
你可以使用cheerio仅选择<script>
标签,然后获取文本并解析它,就像JSON一样:
这是一个示例:
const cheerio = require("cheerio");
const $ = cheerio.load(
`<script type="application/json" class="js-react-on-rails-component" data-component-name="ItemPriceHeading">{"price":"29.0","discountedPrice":null,"offerPrice":null,"totalPrice":"29.0","currency":"PLN"}</script>`
);
const myJSON = JSON.parse(
$('script[data-component-name="ItemPriceHeading"]').text()
);
console.log(myJSON);
myJSON变量应该等于:
{
price: '29.0',
discountedPrice: null,
offerPrice: null,
totalPrice: '29.0',
currency: 'PLN'
}
英文:
You can just select the <script>
tag with cheerio and then get the text and parse it like json:
Here is an example:
const cheerio = require("cheerio");
const $ = cheerio.load(
`<script type="application/json" class="js-react-on-rails-component" data-component-name="ItemPriceHeading">{"price":"29.0","discountedPrice":null,"offerPrice":null,"totalPrice":"29.0","currency":"PLN"}</script>`
);
const myJSON = JSON.parse(
$('script[data-component-name="ItemPriceHeading"]').text()
);
console.log(myJSON);
myJSON variable should be equal to:
{
price: '29.0',
discountedPrice: null,
offerPrice: null,
totalPrice: '29.0',
currency: 'PLN'
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论