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 DevChrome 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();
})();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值