【问题标题】:Node Cheerio returns null节点 Cheerio 返回 null
【发布时间】:2019-08-05 20:40:30
【问题描述】:

我正在尝试网页抓取,但遇到了一些问题。主体有多个 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.js cheerio


    【解决方案1】:

    你的代码没有问题。您尝试抓取的网站通过 AJAX 请求请求大量信息,因此最初的 https://www.funko.com/products/all/categories/the-vault 不会返回您正在寻找的内容。

    如果您将 console.log(html) 添加到您的脚本中,您将看到一个非常精简的版本,因为 AJAX 请求尚未运行。

    【讨论】:

      【解决方案2】:

      正如 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)

      【讨论】:

        猜你喜欢
        • 2016-09-07
        • 2012-06-15
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2017-03-20
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多