木心

毕竟几人真得鹿,不知终日梦为鱼

导航

puppeteer入门

1、demo结构:

 

2、安装puppeteer, 同时安装Chromium

npm i puppeteer

 

 

3、代码

  demo1.js

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch({
        headless: true // 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({
        width: 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:\demo\puppeteer_01> node .\src\demo1.js
PS D:\demo\puppeteer_01> node .\src\demo2.js
PS D:\demo\puppeteer_01> node .\src\demo3.js

  结果:

 

参考:

  1)前端神器puppeteer入门及实践(1)

  2) puppeteer 前端自动化测试踩坑(2)

posted on 2020-01-08 16:14  wenbin_ouyang  阅读(364)  评论(0编辑  收藏  举报