Loading

web前端自动化测试/爬虫利器puppeteer介绍

web前端自动化测试/爬虫利器puppeteer介绍

Intro

Chrome59(linux、macos)、 Chrome60(windows)之后,Chrome自带headless(无界面)模式很方便做自动化测试或者爬虫。但是如何和headless模式的Chrome交互则是一个问题。通过启动Chrome时的命令行参数仅能实现简易的启动时初始化操作。Selenium、Webdriver等是一种解决方案,但是往往依赖众多,不够扁平。

puppeteer

Puppeteer是谷歌官方出品的一个通过DevTools协议控制headless Chrome的Node库。可以通过Puppeteer的提供的api直接控制Chrome模拟大部分用户操作来进行UI Test或者作为爬虫访问页面来收集数据。

Github 仓库:https://github.com/GoogleChrome/puppeteer

安装

Puppeteer本身依赖6.4以上的Node,但是为了异步超级好用的async/await,推荐使用7.6版本以上的Node。另外headless Chrome本身对服务器依赖的库的版本要求比较高,centos服务器依赖偏稳定,v6很难使用headless Chrome,提升依赖版本可能出现各种服务器问题(包括且不限于无法使用ssh),最好使用高版本服务器。

Puppeteer因为是一个npm的包,所以安装很简单:

npm i puppeteer

或者

yarn add puppeteer

Puppeteer 安装时自带一个最新版本的Chromium,可以通过设置环境变量或者npm config中的PUPPETEER_SKIP_CHROMIUM_DOWNLOAD 跳过下载。如果不下载的话,启动时可以通过puppeteer.launch([options])配置项中的 executablePath 指定Chromium的位置。

Use

用 puppeteer 来做什么

Most things that you can do manually in the browser can be done using Puppeteer! Here are a few examples to get you started:

  • Generate screenshots and PDFs of pages.
  • Crawl a SPA (Single-Page Application) and generate pre-rendered content (i.e. "SSR" (Server-Side Rendering)).
  • Automate form submission, UI testing, keyboard input, etc.
  • Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
  • Capture a timeline trace of your site to help diagnose performance issues.
  • Test Chrome Extensions.

大多数在浏览器里手动可以做的事都可以用 puppeteer 来做,比如说:

  • 生成一些网页的截图和 pdf
  • 爬取一个 SPA(单页 WEB 应用)并且生成预渲染内容(比如说过SSR,服务器端渲染)
  • 自动化的表单提交,UI 测试,文本输入等
  • 创建一个现代化的自动化测试环境,在最新版的Chrome 里使用最新的 JavaScript 和浏览器新特性来跑你的测试。
  • 捕获你的网站的 timeline trace 来帮助分析诊断性能问题
  • 测试谷歌扩展插件

你可以在 https://try-puppeteer.appspot.com/ 尝试一些 puppeteer 的功能。

Api 文档:https://github.com/GoogleChrome/puppeteer/blob/v1.10.0/docs/api.md
示例:https://github.com/GoogleChrome/puppeteer/tree/master/examples

Reference

Contact

Contact me: weihanli@outlook.com

posted @ 2018-11-29 11:42  WeihanLi  阅读(1679)  评论(0编辑  收藏  举报