抓取时为什么会得到重复的数据?

时间:2019-08-09 16:13:32

标签: javascript node.js web-scraping puppeteer

我想学习一些网络抓取功能,并且找到了puppeteer库。我选择puppeteer而不是其他工具,因为我对JS有一定的了解。

我还发现了这个website,其目的是要铲除。我已经设法获取每页中每本书的信息。这是我所做的:

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await page.goto(url); // http://books.toscrape.com/

  const json = [];

  let next = await page.$('.pager .next a'); // next button

  while (next) {
    // get all articles
    let articles = await page.$$('.product_pod a');

    // click on each, get data and go back
    for (let index = 0; index < articles.length; index++) {
      await Promise.all([
        page.waitForNavigation(),
        articles[index].click(),
      ]);
      const data = await page.evaluate(getData);
      json.push(data);
      await page.goBack();
      articles = await page.$$('.product_pod a');
    }

    // click the next button
    await Promise.all([
      page.waitForNavigation(),
      page.click('.pager .next a'),
    ]);

    // get the new next button
    next = await page.$('.pager .next a');
  }
  fs.writeFileSync(file, JSON.stringify(json), 'utf8');
  await browser.close();
})();

传递给getData的函数page.evaluate返回具有所需属性的对象:

function getData() {
  const product = document.querySelector('.product_page');
  return {
    title: product.querySelector('h1').textContent,
    price: product.querySelector('.price_color').textContent,
    description:
      document.querySelector('#product_description ~ p')
        ? document.querySelector('#product_description ~ p').textContent
        : '',
    category:
      document.querySelector('.breadcrumb li:nth-child(3) a')
        ? document.querySelector('.breadcrumb li:nth-child(3) a').textContent
        : '',
    cover:
      location.origin +
      document.querySelector('#product_gallery img')
          .getAttribute('src').slice(5),
  };
}

当我最终执行脚本时,除了最后的json文件中有重复的记录之外,一切都进行得很好。也就是说,每本书在文件中都有两个条目。我知道脚本可能会更好,但是您认为这种方法正在发生什么?

1 个答案:

答案 0 :(得分:1)

您在此行中的选择器:

let articles = await page.$$('.product_pod a');

匹配项超出了要求。您得到40个而不是20个(图像容器的a个子标记也与h3的子a相同)

您要限制为h3 a

let articles = await page.$$('.product_pod h3 a');