使用Puppeteer爬取页面数据,以豆瓣的即将上映页面为例

Puppeteer简单介绍

  • Puppeteer 是 Chrome 开发团队在 2017 年发布的一个 Node.js 包,用来模拟 Chrome 浏览器的运行。
  • 它的功能:
    1. 网页截图或者生成 PDF
    2. 爬取 SPA 或 SSR 网站
    3. UI 自动化测试,模拟表单提交,键盘输入,点击等行为
    4. 捕获网站的时间线,帮助诊断性能问题
    5. 创建一个最新的自动化测试环境,使用最新的 js 和最新的 Chrome 浏览器运行测试用例
    6. 测试 Chrome 扩展程序
      ......(不用局限于官方的提示)

Puppeteer的爬虫实现

const puppeteer = require('puppeteer');
const fs = require('fs');

const common = async (workFunc) => {
  const startTime = +new Date();
  console.log(`进入方法`);
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  typeof workFunc === 'function' && await workFunc(page);
  await page.close();
  await browser.close();
  console.log('方法结束,耗费时长:', +new Date() - startTime);
};

const crawler = async (urls, selectors) => {
  const list = [];
  const len = urls.length;
  await common(async (page) => {
    async function runOnce(i) {
      const url = urls[i];
      await page.goto(url);
      const result = await page.evaluate((selectors) => {
        const res = [];
        selectors.forEach(selector => {
          const { key, value, field } = selector;
          const domList = document.querySelectorAll(value);
          Array.prototype.slice.apply(domList).forEach((dom, index) => {
            const newVal = dom[field] || dom.innerText;
            res[index] = res[index] || {};
            res[index][key] = newVal;
          })
        })
        return res;
      }, selectors);
      list.push(...result);
      if (i < len - 1) {
        await runOnce(i + 1);
      }
    }
    await runOnce(0);
  })
  return list;
}

// 使用
const urls = ['https://movie.douban.com/coming'];
const selectors = [
  {
    key: '上映日期',
    value: '.article tr > td:nth-child(1)',
    field: 'innerText'
  },
  {
    key: '片名',
    value: '.article tr > td:nth-child(2)',
    field: 'innerText'
  },
  {
    key: '类型',
    value: '.article tr > td:nth-child(3)',
    field: 'innerText'
  },
  {
    key: '制片国家 / 地区',
    value: '.article tr > td:nth-child(4)',
    field: 'innerText'
  },
  {
    key: '想看',
    value: '.article tr > td:nth-child(5)',
    field: 'innerText'
  }
];
crawler(urls, selectors).then(result => {
  fs.writeFile('豆瓣电影.json', JSON.stringify(result), 'utf-8', err => {
    if (err) {
      console.log(err);
    }
  })
})

/**
最后的结果是这样的
[
  {
    "上映日期": "08月14日",
    "片名": "哈利·波特与魔法石",
    "类型": "奇幻 / 冒险",
    "制片国家 / 地区": "美国 / 英国",
    "想看": "66187人"
  },
  {
    "上映日期": "08月14日",
    "片名": "悲伤逆流成河",
    "类型": "剧情 / 爱情",
    "制片国家 / 地区": "中国大陆",
    "想看": "66005人"
  },
  {
    "上映日期": "08月14日",
    "片名": "通往春天的列车",
    "类型": "爱情",
    "制片国家 / 地区": "中国大陆",
    "想看": "11159人"
  },
  ......
]
*/

小结

  • 小记一下,拓展一下视野,了解一下Puppeteer的基本用法,方便后面有需要的时候能快速上手。
原文地址:https://www.cnblogs.com/aloneMing/p/13470647.html