puppeteer
| const puppeteer = require('puppeteer'); | |||
| 2 | const devices = require('puppeteer/DeviceDescriptors'); | ||
| 3 | |||
| 4 | const PICT_PATH= './img'; | ||
| 5 | //项目启动web地址 | ||
| 6 | const WEB_PATH ='http://localhost:3000/#!pages/index/index'; | ||
| 7 | |||
| 8 | |||
| 9 | (async () => { | ||
| 10 | const browser = await puppeteer.launch(); | ||
| 11 | const page = await browser.newPage(); | ||
| 12 | //设置展示的设备https://github.com/GoogleChrome/puppeteer/blob/master/DeviceDescriptors.js | ||
| 13 | //await page.emulate(devices['iPhone 6']); | ||
| 14 | //多一个参数waitUntil,指跳转之后等待网络空闲之后再执行下一步操作,没有这个的话,截图很有可能是白屏,因为内容还没渲染出来 | ||
| 15 | await page.goto('http://localhost:3000/#!pages/index/index'); | ||
| 16 | // //await page.goto('https://example.com'); | ||
| 17 | //小程序的内容其实是放在一个iframe里面,外面是无法直接抓取到iframe里面的内容,所以这里需要获取页面所有的iframe | ||
| 18 | //const frames = await page.frames(); | ||
| 19 | const weChatFrame = await page.$('#view-0');; | ||
| 20 | //console.log(frames); | ||
| 21 | // //根据iframe的name属性来获取正确的iframe | ||
| 22 | //const weChatFrame = frames.find(f => f.name() === 'view-0'); | ||
| 23 | //console.log(weChatFrame); | ||
| 24 | // //在上下文环境中获取需要抓取的内容 | ||
| 25 | // const outerText = await page.evaluate(() => { | ||
| 26 | // //上下文执行环境,跟H5一致 | ||
| 27 | // const anchors = Array.from(document.querySelectorAll('.container')); | ||
| 28 | // return anchors.map(anchor => anchor.textContent); | ||
| 29 | // }); | ||
| 30 | // console.log('the outerText: ', anchors); | ||
| 31 | await page.screenshot({path: 'example.png'}); | ||
| 32 | await browser.close(); | ||
| 33 | // //await page.screenshot({path: 'example.png'}); | ||
| 34 | |||
| 35 | //await browser.close(); | ||
| 36 | |||
| 37 | |||
| 38 | |||
| 39 | // const browser = await puppeteer.launch(); | ||
| 40 | // const page = await browser.newPage(); | ||
| 41 | // await page.goto('https://example.com'); | ||
| 42 | // await page.screenshot({path: 'example.png'}); | ||
| 43 | |||
| 44 | // await browser.close(); | ||
| 45 | })(); |