我正在使用 Nodejs 和 Cheerio 包来收集网站上的信息,在迭代将信息存储到数组中后,我很难收集信息。
在此示例中我要收集的文本是“George Ezra - Wanted On Voyage(LP、专辑 + CD、专辑)”
我当前正在迭代具有“shortcut_navigable”类的元素,并希望将每个标题存储在数组中。
到目前为止,我还无法通过此代码示例收集文本。
axios(url)
.then(response => {
const html = response.data
const $ = cheerio.load(html)
const articles = []
$('.shortcut_navigable', html).each(function() {
const title = $(this).find('a').has('.item_description').text()
articles.push({
title,
})
})
console.log(articles)
}).catch(err => console.log(err))
我希望能够将具有“item_description_title”类的元素的所有标题存储在数组中,然后能够存储其他信息。
非常感谢任何建议和帮助,谢谢。
如果我猜对了你的网址,
has
似乎没有必要。您可以直接使用.find()
中的类名。
这是一个帮助您入门的示例:
const axios = require("axios"); // 1.4.0
const cheerio = require("cheerio"); // 1.0.0-rc.12
const url = "https://www.discogs.com/sell/release/5840245?ev=rb";
axios
.get(url)
.then(({data: html}) => {
const $ = cheerio.load(html);
const data = [...$(".shortcut_navigable")].map(e => ({
title: $(e).find(".item_description_title").text().trim(),
seller: $(e).find(".seller_block a").text().trim(),
price: +$(e).find("[data-pricevalue]").data("pricevalue"),
shipping: $(e).find(".item_shipping").contents().get(0).data.trim(),
// ...etc...
}));
console.log(data);
})
.catch((err) => console.error(err));
顺便说一句,发布文字而不是屏幕截图是个好主意。 Axios 和 Cheerio 不执行 JS,因此屏幕截图中显示的开发工具可能会产生误导,因为它显示页面加载后动态创建的元素。
view-source:
更好地表示了您可能通过 axios 得到的结果(或者简单地打印 axios 提供的响应正文)。幸运的是,JS 似乎不是您目前正在使用的网站的这一部分的一个因素,但值得记住。