1. 程式人生 > >web前端自動化測試利器puppeteer介紹

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: [email protected]