溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

手動(dòng)下載Chrome并解決puppeteer無法使用問題

發(fā)布時(shí)間:2020-08-28 20:23:08 來源:腳本之家 閱讀:769 作者:Marx 欄目:web開發(fā)

因?yàn)榫W(wǎng)絡(luò)原因,國內(nèi)安裝 puppeteer 的時(shí)候會(huì)報(bào)網(wǎng)絡(luò)超時(shí)。這里使用 puppeteer-core 之后使用手動(dòng)下載的 Chrome 進(jìn)行操作。思路很簡單,安裝一個(gè)不帶瀏覽器的 puppeteer ,再使用的時(shí)候?qū)g覽器地址指向一個(gè)可執(zhí)行的 Chrome 瀏覽器文件。

安裝

安裝 puppeteer-core

yarn add puppeteer-core

找到 puppeteer 中對(duì)應(yīng)的瀏覽器并下載

node_modules/puppeteer-core/lib/BrowserFetcher.js 中找到各平臺(tái) Chrome 下載地址。其中 %s 替換為 DEFAULT_DOWNLOAD_HOST 的值, %d 替換為版本號(hào)。

手動(dòng)下載Chrome并解決puppeteer無法使用問題

node_modules/puppeteer-core/packages.json 中找到版本號(hào)

手動(dòng)下載Chrome并解決puppeteer無法使用問題

替換后得到下載地址

https://storage.googleapis.com/chromium-browser-snapshots/Mac/579032/chrome-mac.zip

下載后解壓,放在項(xiàng)目目錄中,這里我放在 chrome 下。

使用

這樣就可以使用了。

使用代碼

const puppeteer = require('puppeteer-core');
const path = require('path');

(async () => {
 const browser = await puppeteer.launch({
  // 這里注意路徑指向可執(zhí)行的瀏覽器。
  // 各平臺(tái)路徑可以在 node_modules/puppeteer-core/lib/BrowserFetcher.js 中找到
  // Mac 為 '下載文件解壓路徑/Chromium.app/Contents/MacOS/Chromium'
  // Linux 為 '下載文件解壓路徑/chrome'
  // Windows 為 '下載文件解壓路徑/chrome.exe'
  executablePath: path.resolve('./chrome/Chromium.app/Contents/MacOS/Chromium')
 });
 const page = await browser.newPage();
 await page.setViewport({
  width: 375,
  height: 667,
  deviceScaleFactor: 1,
  isMobile: true
 })
 await page.goto('https://marxjiao.com/');
 await page.screenshot({path: 'marx-blog.png'});
 await browser.close();
})();

執(zhí)行文件

node index.js

執(zhí)行后可看到,圖片已經(jīng)截圖出來了

手動(dòng)下載Chrome并解決puppeteer無法使用問題

代碼地址:https://github.com/MarxJiao/puppeteer-test

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI