puppeteerExamples

What can I do?

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

  1. Generate screenshots and PDFs of pages.
  2. Crawl a SPA and generate pre-rendered content (i.e. "SSR").
  3. Automate form submission, UI testing, keyboard input, etc.
  4. 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.
  5. Capture a timeline trace of your site to help diagnose performance issues.

例子说明:

const puppeteer = require('puppeteer'); // 导入puppeteer库
(async () => { //固定语法格式
  const browser = await puppeteer.launch(); //根据puppeteer创建一个Browser对象,相当于启动了浏览器
  //const browser = await puppeteer.launch({headless:false}); //相当于以可视的方式启动了浏览器,headless默认为true
  //const browser = await puppeteer.launch({executablePath:'/Volumes/A/chrome'});//引用其它谷歌chrome版本,但兼容性很差,只适用于Chrome Dev或Chrome Canary 
  const page = await browser.newPage(); //根据Browser创建一个Page对象,相当于打开一个标签页
  await page.goto('https://example.com'); //page.goto()跳转到指定url地址
  await page.screenshot({path: 'example.png'}); //page.screenshot()对页面进行截图
  await browser.close(); //关闭浏览器
})();

// Example1 - navigating to https://example.com and saving a screenshot as example.png.截取网页为png图片

const puppeteer = require("puppeteer");
(async () =>{
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page.screenshot({path:'example.png'});
    await browser.close();
})();

// Example2 - create a PDF.将网页生存PDF格式文档

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  //await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
  await page.goto('https://www.baidu.com', {waitUntil: 'networkidle2'});
  await page.pdf({path: 'hn0.pdf', format: 'A4'});

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

//Example3 - evaluate script in the context of the page,打印网页信息

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.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();
})();
posted @ 2019-06-03 19:34  HenryZ.Tang  阅读(257)  评论(0编辑  收藏  举报