跳至主要内容

Puppeteer 使用总结

Puppeteer 使用总结

Puppeteer 使用总结

介绍

从字面单词上的意思是'提线木偶', 它是一个node库,为我们提供了很多高级API来控制Chrome, 即 Headless Chrome 无界面浏览器。 之前我们在做项目的集成的时候大部分用的都是PhantomJS, 这个库和Puppeteer的功能是一样的, 但是现在有了Pupperteer, PhantomJS已经停止维护了, 毕竟是Chrome 官方出品。

功能

  • 用来做集成测试
  • 获取网页截图或导出PDF
  • 抓取网页内容(SPA)
  • ...

安装

npm i puppeteer

yarn add puppeteer

安装puppeteer时会在本地下载Chromium, 体积较大所以请耐心等待。

使用

示例代码

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'example.png'});

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

高级使用:

参考官方文档: Puppetter Docs

在Centos中使用

首先需要在运行时添加如下参数:

browser = await puppeteer
  .launch({
    args:
    [
      '--no-sandbox',
      '--disable-setuid-sandbox'
    ]
  })

其次 Puppteer在运行时会进行大量图形运算与渲染, 一般Centos是没有安装这些依赖的,需要手动安装.

yum install ipa-gothic-fonts xorg-x11-fonts-100dpi xorg-x11-fonts-75dpi xorg-x11-utils xorg-x11-fonts-cyrillic xorg-x11-fonts-Type1 xorg-x11-fonts-misc -y
yum install pango.x86_64 libXcomposite.x86_64 libXcursor.x86_64 libXdamage.x86_64 libXext.x86_64 libXi.x86_64 libXtst.x86_64 cups-libs.x86_64 libXScrnSaver.x86_64 libXrandr.x86_64 GConf2.x86_64 alsa-lib.x86_64 atk.x86_64 gtk3.x86_64 ipa-gothic-fonts xorg-x11-fonts-100dpi xorg-x11-fonts-75dpi xorg-x11-utils xorg-x11-fonts-cyrillic xorg-x11-fonts-Type1 xorg-x11-fonts-misc -y

通常安装完成后就已经可以正常运行,若还是不行,最有可能是glib2这个库的版本问题,更新这个库的版本即可 yum update glib2.

若使用Docker运行, 我已经打包了一个centos, 直接可以运行puppeteer, Centos-Puppeteer.

性能优化

大家都知道Node的特点是适合IO密集型任务, 弱项是CPU密集型任务, 但是Puppeteer恰好是CPU密集型,因此性能优化是非常重要,否则当并发量(QPS)大的时候,Puppeteer将会直接不可用(CPU使用率过高导致浏览器崩溃)。 本文主要从两个方面来进行性能优化(部分内容引用自Puppeteer性能优化与执行速度提升)

初始化提前

在 Puppeteer 使用中我们使用最多的是Page, 因此我们可以在服务启动时提前启动浏览器,在请求时只需要创建新的Page页即可, 不必要每次都启动服务器。

取消不必要启动项

Puppeteer 启动时禁用掉不必要的功能,以此来减少单此请求的时间, 提高性能。

优化后启动参数列表:

const browser = await puppeteer
  .launch({
    userDataDir,
    args:
    [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '–disable-gpu',
      '–disable-dev-shm-usage',
      '–no-first-run',
      '–no-zygote',
      '–single-process'
    ]
  })

增加整体服务的稳定性

Puppeteer的性能瓶颈是: 当并发量过高时,CPU使用率瞬间升高,导致页面阻塞,使浏览器崩溃。所以,我们可以控制当前服务器上的并发量,保证其在服务器可支持最大并发量的阀值之下,后续的请求可以以队列方式串行,这样可以保证所有的请求都可以正常请求(需要牺牲请求执行时间),保证服务的稳定性,从而来提升性能。

为了控制Puppeteer的并发请求,我在npm找到了一个库,来实现此功能: Puppeteer-Cluster。这个库会创建多个页面并且重复利用这些页面,以此来提高性能,另外可以控制最大并发数等等,具体使用可参考其文档,这样以来我们在保证服务稳定的前提下使并发达到最大。

代码示例:

const { Cluster } = require('puppeteer-cluster');

(async () => {
    // Create a cluster with 2 workers
    const cluster = await Cluster.launch({
        maxConcurrency: 2,
    });

    // Define a task
    await cluster.task(async ({ page, data: url }) => {
        await page.goto(url);
        const pageTitle = await page.evaluate(() => document.title);
        return pageTitle;
    });

    // Use try-catch block as "execute" will throw instead of using events
    try {
        // Execute the tasks one after another via execute
        const result1 = await cluster.execute('https://www.google.com');
        console.log(result1);
        const result2 = await cluster.execute('https://www.wikipedia.org');
        console.log(result2);
    } catch (err) {
        // Handle crawling error
    }

    // Shutdown after everything is done
    await cluster.idle();
    await cluster.close();
})();

评论

  1. Gambling in NJ - JTHub
    In New Jersey, the state 의정부 출장안마 legalized online sports 김제 출장안마 betting, 수원 출장마사지 casinos can still be legally run on a gambling platform, but gambling laws 이천 출장안마 are not in 광주 출장마사지 the

    回复删除
  2. This welcome bonus is for keno and slots on line casino games only, the minimum deposit required is $30, and the wagering requirement 카지노사이트 is a rollover of just 5x. Read the terms and situations rigorously search out|to search out} essentially the most appropriate bonus for you and which recreation presents the lowest wagering requirements. Several on-line casinos provide wager-free bonuses or free spins as a substitute of a deposit bonus package. These free spins live up to as} their name for being "completely free" since they do not include any wagering requirements.

    回复删除

发表评论