nodejs puppeteer pdf下载

linux安装 略;

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  var route = process.argv[2];
  var pageName = process.argv[3];
  await page.goto(route, {waitUntil: 'networkidle2'});
  await page.pdf({ path: pageName, scale: 1, landscape: true, printBackground: true, format: "A4", preferCSSPageSize: true, displayHeaderFooter: false, margin: { left: "10mm", right:"9.5mm",top:"10mm",bottom:"9.5mm"}})

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

 自定义浏览器和puppeteer路径

报错:

(node:6350) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!
[0425/111753.410288:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.


TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md

    at onClose (/root/node_modules/puppeteer/lib/Launcher.js:342:14)
    at Interface.helper.addEventListener (/root/node_modules/puppeteer/lib/Launcher.js:331:50)
    at Interface.emit (events.js:194:15)
    at Interface.close (readline.js:379:8)
    at Socket.onend (readline.js:157:10)
    at Socket.emit (events.js:194:15)
    at endReadableNT (_stream_readable.js:1125:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
(node:6350) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or b
y rejecting a promise which was not handled with .catch(). (rejection id: 1)(node:6350) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js pr
ocess with a non-zero exit code.

引用浏览器设置   args: ['--no-sandbox', '--disable-setuid-sandbox']

  const puppeteer = require('/root/node_modules/puppeteer');
 const path = require('path');

(async () => {
 //   const browser = await puppeteer.launch(); 
	  const browser = await puppeteer.launch({
  // 这里注意路径指向可执行的浏览器。
  // 各平台路径可以在 node_modules/puppeteer-core/lib/BrowserFetcher.js 中找到
  // Mac 为 '下载文件解压路径/Chromium.app/Contents/MacOS/Chromium'
  // Linux 为 '下载文件解压路径/chrome'
  // Windows 为 '下载文件解压路径/chrome.exe'
  args: ['--no-sandbox', '--disable-setuid-sandbox'],
  executablePath: path.resolve('/root/node_modules/puppeteer/.local-chromium/linux-641577/chrome-linux/chrome')
 });
  const page = await browser.newPage();
  var route = process.argv[2];
  var pageName = process.argv[3];
  await page.goto(route, {waitUntil: 'networkidle2'});
  await page.pdf({ path: pageName, scale: 1, landscape: true, printBackground: true, format: "A4", preferCSSPageSize: true, displayHeaderFooter: false, margin: { left: "10mm", right:"9.5mm",top:"10mm",bottom:"9.5mm"}})

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

 完成。

 

上一篇:nodejs puppeteer linux(centos)环境部署以及用puppeteer简单截图


下一篇:爬虫利器 Puppeteer 实战