【问题标题】:How do you get all the links from a page with node puppeteer?您如何使用节点 puppeteer 从页面获取所有链接?
【发布时间】:2019-05-16 19:48:40
【问题描述】:

我正在尝试使用 node 构建一个网络爬虫,并遇到了 puppeteer 包,它看起来非常适合我想要的东西。我的最终结果是收集页面中的所有链接、所有文本内容,然后是页面本身的屏幕截图。

我运行了以下内容,它似乎收集了大量链接,但是在实际检查该站点时,有一些链接没有收集。

const puppeteer = require('puppeteer');

module.exports = () => {
  (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://pixabay.com/en/columbine-columbines-aquilegia-3379045/');
    await page.screenshot({ path: 'myscreenshot.png', fullPage: true });
    let text = await page.$eval('*', el => el.innerText.split(' '));
    text = text.map(string => {
      return string.replace(/[^\w\s]/gi, '');
    });

      let hrefs = await page.evaluate(() => {
          const links = Array.from(document.querySelectorAll('a'))
          return links.map(link => link.href);
      });
    console.log('done');

    await browser.close();
  })();
};

例如此链接:/go/?t=image-details-shutterstock&id=699165328 在 href 数组中不存在。更糟糕的是,这些是指向网站外的链接,正是我想做的事情的类型,否则我只能抓取一个网站。

我的脚本只显示一些链接是有原因的吗? querySelector 是否太窄或拒绝某些链接?

【问题讨论】:

    标签: javascript node.js web-scraping web-crawler puppeteer


    【解决方案1】:

    链接由onclick事件生成,例如保存在data-go属性中

    <a data-go="image-details-shutterstock&amp;id=458320033">
    

    只需要在前面加上/go/?t=就可以了

    return links.map(link => link.href || link.getAttribute('data-go'));
    

    菜单也有空链接

    <a><i class="icon icon_menu_user"></i></a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 2017-04-17
      • 1970-01-01
      相关资源
      最近更新 更多