我正在试着抓取网页,但遇到了一些麻烦。主体有多个div,其中有一个名为.details的类。我正在尝试将HTML放入这些div中。
我的代码在下面,但它在控制台中记录null。我做错了什么?
var url = "https://www.funko.com/products/all/categories/the-vault";
request(url, function(err, response, html) {
if (!err && response.statusCode == 200){
let $ = cheerio.load(html);
const tag = $('.details');
console.log(tag.html());
$('.details').each((i,element)=>{
console.log(element);
});
} else {
console.log(error);
}
});发布于 2019-03-15 05:26:02
这不是你的代码的问题。您试图抓取的网站通过AJAX请求请求大量信息,因此最初的https://www.funko.com/products/all/categories/the-vault不会返回您要查找的内容。
如果将console.log(html)添加到脚本中,您将看到一个非常精简的版本,因为AJAX请求还没有运行。
发布于 2019-03-15 17:32:09
正如sketchthat所指出的,cheerio在这里帮不了你太多。
要获取商品数据,您需要先获取collection_id:
$ curl -s 'https://www.funko.com/ui-api/cms/tables/collections/rows' | json -a data | json -c 'this.handle=="the-vault"' -a collection_id
199936515然后使用id,您可以获取所需的json数据:
$ curl -s 'https://www.funko.com/ui-api/search?page=1&limit=15&&collectionId=199936515' | json 'products[0]'
{
"id": "10883713155",
"title": "Pop! Marvel: Phoenix/Jean Grey",
"handle": "pop-marvel-phoenix-jean-grey",
"product_type": "Pop!",
"tags": "The Vault",
"image": {
"src": "https://cdn.shopify.com/s/files/1/0552/1401/products/Green_Phoenix_POP_CMYK_GLAM_grande_bd258ee0-0064-4573-ace4-111e01437590.jpg?v=1505506339"
},
"variants": [
{
"sku": "VAULTED"
}
]
}(这些示例假设您已经通过npm -g i json安装了'json‘cli util )
https://stackoverflow.com/questions/55171220
复制相似问题