无法使用 Cheerio 抓取某些元素

Unable to scrape certain elements with Cheerio

我正在尝试使用 pupeteer 和 Cheerio 抓取产品页面。 (this page)

我正在使用数据 ID 抓取标题和图片。问题是标题永远不会被抓取,而图像每次都会抓取。

我试过通过 class 名称抓取标题,但这也不起作用。这与我要抓取的特定网站有关吗?谢谢。

我的代码:

    // Load cheerio
    const $ = cheerio.load(data);
    
    /* Scrape Product Page */
    const product = [];
    
    // Title
    $('[data-testid="product-name"]').each(() => {
       product.push({
         title: $(this).text(),
       });
    });
    
     // Image
     $('[data-testid="product-detail-image"]').each((index, value) => {
          const imgSrc = $(value).attr('src');
           product.push({
             image: imgSrc,
           });
      });

正如我在评论中提到的,我认为几乎没有任何用例同时适用于 Puppeteer 和 Cheerio。如果数据是静态的,请将 Cheerio 与简单的请求库(如 Axios)一起使用,否则使用 Puppeteer 并完全跳过 Cheerio,转而使用原生 Puppeteer 选择器。

使用 Puppeteer 的另一个潜在原因是,如果您的请求库被服务器的机器人检测器阻止,就像这里的情况一样。

这个脚本对我有用:

const puppeteer = require("puppeteer");

let browser;
(async () => {
  browser = await puppeteer.launch({headless: true});
  const [page] = await browser.pages();
  const url = "https://stockx.com/nike-air-force-1-low-white-07";
  await page.goto(url);

  const nameSel = '[data-testid="product-name"]';
  await page.waitForSelector(nameSel, {timeout: 60000});
  const name = await page.$eval(nameSel, el => el.textContent);

  const imgSel = '[data-testid="product-detail-image"]';
  await page.waitForSelector(imgSel);
  const src = await page.$eval(imgSel, el => el.src);

  console.log(name, src);
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;