首页 > 解决方案 > 节点 Cheerio 返回 null

问题描述

我正在尝试网页抓取,但遇到了一些麻烦。主体有多个 div,类名为.details. 我正在尝试在这些 div 中获取 HTML。

我的代码在下面,但它会登录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);
  }
});

标签: node.jscheerio

解决方案


正如 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"
    }
  ]
}

(示例假设您已通过 'json' cli util 安装npm -g i json


推荐阅读