【问题标题】:Webscraping walmarts products with cheerio用 Cheerio 抓取沃尔玛的产品
【发布时间】:2020-04-11 21:42:19
【问题描述】:

我正在尝试抓取 walmart 的产品。这是我试图拉出的链接 https://www.walmart.com/search/?query=&cat_id=91083 我能够成功地从页面上抓取 10 种产品。这是我正在使用的代码。

const axios = require('axios');
const cheerio = require('cheerio');

axios.get('https://www.walmart.com/search/?query=&cat_id=91083').then( res => {
        var combino1 = [];
        const $ = cheerio.load(res.data);

        $('a.product-title-link').each( (index, element) => {
        const name = $(element)
        .first().text()
        combino1[index] = {name}
        })
        console.log(combino1);
    })

当我使用 a.product-title-link 搜索 dom 时,它会显示 40 个产品。为什么我只能抓到 10 个而不是 40 个?

【问题讨论】:

  • 是的,仍然只输出 10 个产品
  • 等等,不,我没有做你做的事,它说了别的

标签: javascript dom cheerio


【解决方案1】:

您的问题是使用 axios 的调用只会让您获得服务器提供的 HTML

这意味着任何从系统其他部分获取产品的异步调用都不会出现在该请求中

将接收到的数据简单地输出到新文件中,将显示这一事实

const fs = require('fs')
...
fs.writeFileSync('./data.html', res.data)

打开新的data.html 文件只会输出10 作为找到的product-title-link 的编号

为此,您不能使用axios,而是使用Web scraper 库,例如Puppeteer,您可以等待所有产品加载完毕,然后再遍历DOM在那个特定的时间。

【讨论】:

  • 好吧,是的,我做到了。但是如何遍历查询选择器呢?
  • 这不是你的问题,你的问题是你为什么只得到 10 种产品 :) - 正如我所说,你不能使用 axios 看看 Puppeteer,即使在 youtube 上所以你明白如何使用它
猜你喜欢
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
相关资源
最近更新 更多