• puppeteer入门


    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

      结果:

     

    参考:

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

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

  • 相关阅读:
    HTTP协议 学习笔记一
    web发展历史
    Easydarwin加FFMPEG实现HLS流视频点播
    C# Socket异步实现消息发送--附带源码
    C# Activex调用USB摄像头--附带源码
    C# listbox DataSource数据绑定--一年半以前的bug
    ASP.NET MVC WebAPI实现文件批量上传
    ASP.NET MVC使用SignalR统计在线用户人数
    Chart.js Y轴数据以百分比展示
    Java获取字符串信息
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12167226.html
Copyright © 2020-2023  润新知