Node.js 之 Puppeteer

Puppeteer

中文文檔:https://zhaoqize.github.io/puppeteer-api-zh_CN/#/
在這裏插入圖片描述

出現的背景

Chrome59(linux、macos)、 Chrome60(windows)之後,Chrome自帶headless(無界面)模式很方便做自動化測試或者爬蟲。但是如何和headless模式的Chrome交互則是一個問題。通過啓動Chrome時的命令行參數僅能實現簡易的啓動時初始化操作。Selenium、Webdriver等是一種解決方案,但是往往依賴衆多,不夠扁平。

Puppeteer是谷歌官方出品的一個通過DevTools協議控制headless Chrome的Node庫。可以通過Puppeteer的提供的api直接控制Chrome模擬大部分用戶操作來進行UI Test或者作爲爬蟲訪問頁面來收集數據。

作用

能做什麼?
  • 生成頁面 PDF。
  • 抓取 SPA(單頁應用)並生成預渲染內容。
  • 自動提交表單,進行 UI 測試,鍵盤輸入等。
  • 創建一個時時更新的自動化測試環境。 使用最新的 JavaScript 和瀏覽器功能直接在最新版本的Chrome中執行測試。
  • 捕獲網站的 timeline trace,用來幫助分析性能問題。
  • 測試瀏覽器擴展。

環境和安裝

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的位置。

使用和例子

Puppeteer類似其他框架,通過操作Browser實例來操作瀏覽器作出相應的反應。

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://rennaiqian.com');
  await page.screenshot({path: 'example.png'});
  await page.pdf({path: 'example.pdf', format: 'A4'});
  await browser.close();
})();

上述代碼通過puppeteer的launch方法生成了一個browser的實例,對應於瀏覽器,launch方法可以傳入配置項,比較有用的是在本地調試時傳入{headless:false}可以關閉headless模式。

const browser = await puppeteer.launch({headless:false})

browser.newPage方法可以打開一個新選項卡並返回選項卡的實例page,通過page上的各種方法可以對頁面進行常用操作。上述代碼就進行了截屏和打印pdf的操作。
一個很強大的方法是page.evaluate(pageFunction, …args),可以向頁面注入我們的函數,這樣就有了無限可能

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://rennaiqian.com');
  // Get the "viewport" of the page, as reported by the page.
  const dimensions = await page.evaluate(() => {
    return {
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
      deviceScaleFactor: window.devicePixelRatio
    };
  });
  console.log('Dimensions:', dimensions);
  await browser.close();
})();

需要注意的是evaluate方法中是無法直接使用外部的變量的,需要作爲參數傳入,想要獲得執行的結果也需要return出來。因爲是一個開源一個多月的項目,現在項目很活躍,所以使用時自行查找api才能保證參數、使用方法不會錯。

調試技巧

  1. 關掉無界面模式,有時查看瀏覽器顯示的內容是很有用的。使用以下命令可以啓動完整版瀏覽器:
const browser = await puppeteer.launch({headless: false})
  1. 減慢速度,slowMo選項以指定的毫秒減慢Puppeteer的操作。這是另一個看到發生了什麼的方法:
const browser = await puppeteer.launch({
  headless:false,
  slowMo:250
});

3.捕獲console的輸出,通過監聽console事件。在page.evaluate裏調試代碼時這也很方便:

page.on('console', msg => console.log('PAGE LOG:', ...msg.args));
await page.evaluate(() => console.log(`url is ${location.href}`));

4.啓動詳細日誌記錄,所有公共API調用和內部協議流量都將通過puppeteer命名空間下的debug模塊進行記錄

# Basic verbose logging
 env DEBUG="puppeteer:*" node script.js
 # Debug output can be enabled/disabled by namespace
 env DEBUG="puppeteer:*,-puppeteer:protocol" node script.js # everything BUT protocol messages
 env DEBUG="puppeteer:session" node script.js # protocol session messages (protocol messages to targets)
 env DEBUG="puppeteer:mouse,puppeteer:keyboard" node script.js # only Mouse and Keyboard API calls
 # Protocol traffic can be rather noisy. This example filters out all Network domain messages
 env DEBUG="puppeteer:*" env DEBUG_COLORS=true node script.js 2>&1 | grep -v '"Network'

爬蟲實踐

很多網頁通過user-agent來判斷設備,可以通過page.emulate(options)來進行模擬。options有兩個配置項,一個爲userAgent,另一個爲viewport可以設置寬度(width)、高度(height)、屏幕縮放(deviceScaleFactor)、是否是移動端(isMobile)、有無touch事件(hasTouch)。

const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iPhone = devices['iPhone 6'];
puppeteer.launch().then(async browser => {
  const page = await browser.newPage();
  await page.emulate(iPhone);
  await page.goto('https://www.example.com');
  // other actions...
  await browser.close();
});

上述代碼則模擬了iPhone6訪問某網站,其中devices是puppeteer內置的一些常見設備的模擬參數。
很多網頁需要登錄,有兩種解決方案:

  1. 讓puppeteer去輸入賬號密碼常用方法:點擊可以使用page.click(selector[, options])方法,也可以選擇聚焦page.focus(selector)。輸入可以使用page.type(selector, text[, options])輸入指定的字符串,還可以在options中設置delay緩慢輸入更像真人一些。也可以使用keyboard.down(key[, options])來一個字符一個字符的輸入。
  2. 如果是通過cookie判斷登錄狀態的可以通過page.setCookie(…cookies),想要維持cookie可以定時訪問。
Tip:有些網站需要掃碼,但是相同域名的其他網頁卻有登錄,就可以嘗試去可以登錄的網頁登錄完利用cookie訪問跳過掃碼。

簡單例子

打開瀏覽器,百度搜索“Node.js” 進入“菜鳥教程”,然後再關閉瀏覽器

實現:

  1. 創建pu.js文件
const puppeteer = require('puppeteer');
(async () => {
    //打開瀏覽器
  const browser = await puppeteer.launch({headless: false});
  //打開新的標籤頁
  const page = await browser.newPage();
  //將打開的標籤頁跳轉到百度首頁。
  await page.goto('https://baidu.com');
  //在百度搜索輸入框中輸入 "Node.js" 關鍵字
  await page.type('#kw', 'Node.js', {delay: 100});
  //執行點擊搜索按鈕
  page.click('#su')
  await page.waitFor(1000);
  //在搜索結果中遍歷標題包含“菜鳥教程”關鍵字的鏈接
  const targetLink = await page.evaluate(() => {
    return [...document.querySelectorAll('.result a')].filter(item => {
       //取搜索結果中 標題包含“菜鳥教程”關鍵字的鏈接
      return item.innerText && item.innerText.includes('菜鳥教程')
    })[0].toString()//如果結果有多條,只取第1條,並轉爲string返回
  });
  //當前頁面跳轉到搜索結果返回的鏈接
   await page.goto(targetLink);
  await page.waitFor(1000);
  //關鍵瀏覽器
  browser.close();
})()
  1. 在控制檯輸入命令執行
node pu.js

效果如下
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章