1、demo结构:
2、安装puppeteer, 同时安装Chromium
npm i puppeteer
3、代码
demo1.js
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: true }) const page = await browser.newPage() await page.goto('http://www.baidu.com') await page.screenshot({ path: 'd:/temp/baidu.png' }) await browser.close(); // 关闭浏览器 })()
demo2.js
const devices = require('puppeteer/DeviceDescriptors') const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: true }) const page = await browser.newPage() await page.emulate(devices['iPhone X']) await page.goto('http://www.baidu.com') await page.screenshot({ path: 'd:/temp/baidu_iphone_X.png' }) await browser.close(); // 关闭浏览器 })()
demo3.js
// const devices = require('puppeteer/DeviceDescriptors') const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false }) const page = await browser.newPage() page.setViewport({ 1920, height: 969, }); // await page.emulate(devices['iPhone X']) await page.goto('http://www.baidu.com') await page.type('#kw', 'puppeteer') await page.click('#su') // await page.waitForNavigation({ timeout: 5000 }) await page.waitFor(3000) await page.screenshot({ path: 'd:/temp/baidu_search_puppeteer.png' }) // page.waitForSelector('.nums_text') // .then(() => { // page.screenshot({ // path: 'd:/temp/baidu_search_puppeteer.png' // }) // }) await browser.close(); // 关闭浏览器 })()
4、测试
执行命令:
PS D:demopuppeteer_01> node .srcdemo1.js
PS D:demopuppeteer_01> node .srcdemo2.js
PS D:demopuppeteer_01> node .srcdemo3.js
结果:
参考: