Home Web Front-end JS Tutorial A brief analysis of how to use the Puppeteer library in Node.js

A brief analysis of how to use the Puppeteer library in Node.js

Dec 10, 2021 pm 06:56 PM
node.js

What is the Puppeteer library? What can be done? how to use? The following article will introduce you to the Puppeteer library and learn how to use the Puppeteer library in Node.js. I hope it will be helpful to you!

A brief analysis of how to use the Puppeteer library in Node.js

Puppeteer is a officially produced by Google that controls headless Chrome through the DevTools protocol Node Library. You can directly control Chrome through the API provided by Puppeteer to simulate most user operations to perform UI Test or access the page as a crawler to collect data.

Chinese documentation

https://zhaoqize.github.io/puppeteer-api-zh_CN/#/

Function:

What can it do?

  • Generate page PDF.
  • Crawl SPA (Single Page Application) and generate pre-rendered content.
  • Automatically submit forms, perform UI testing, keyboard input, etc.
  • Create an automated testing environment that is constantly updated. Execute tests directly in the latest version of Chrome using the latest JavaScript and browser features.
  • Capture the timeline trace of the website to help analyze performance issues.
  • Test the browser extension.

Puppeteer is an npm package, so the installation is very simple:

npm i puppeteer
Copy after login

or

yarn add puppeteer
Copy after login

How to use:

// 引入 Puppeteer 模块
let puppeteer = require('puppeteer')

//puppeteer.launch实例化开启浏览器
async function test() {
    //可以传入一个options对象({headless: false}),可以配置为无界面浏览器,也可以配置有界面浏览器
    //无界面浏览器性能更高更快,有界面一般用于调试开发
    let options = {
        //设置视窗的宽高
        defaultViewport:{
            width:1400,
            height:800
        },
        //设置为有界面,如果为true,即为无界面
        headless:false,
        //设置放慢每个步骤的毫秒数
        slowMo:250
    }
    let browser = await puppeteer.launch(options);

    // 打来新页面
    let page = await browser.newPage();

    // 配置需要访问网址
    await page.goto('http://www.baidu.com')
    
    // 截图
    await page.screenshot({path: 'test.png'});

    //打印pdf
    await page.pdf({path: 'example.pdf', format: 'A4'});

   // 结束关闭
    await browser.close();
}test()
Copy after login

A brief analysis of how to use the Puppeteer library in Node.js

// 获取页面内容
//$$eval函数,使回调函数可以运行在浏览器中,并且可以通过浏览器的方式进行输出
    await page.$$eval('#head #s-top-left a',(res) =>{
        //console.log(res);
        res.forEach((item,index) => {
            console.log($(item).attr('href'));
        })
    })
// 监听console.log事件
page.on('console',(...args) => {
    console.log(args);
})
// 获取页面对象,添加点击事件
   ElementHandle = await page.$$('#head #s-top-left a')
   ElementHandle[0].click();
Copy after login

A brief analysis of how to use the Puppeteer library in Node.js

// 通过表单输入进行搜索
    inputBox = await page.$('#form .s_ipt_wr #kw')
    await inputBox.focus() //光标定位在输入框
    await page.keyboard.type('Node.js') //向输入框输入内容
    search = await page.$('.s_btn_wr input[type=submit]')
    search.click() //点击搜索按钮
Copy after login

A brief analysis of how to use the Puppeteer library in Node.js

Crawler practice

Many web pages use user-agent to determine the device. You can use page.emulate(options) to perform simulation. options has two configuration items, one is userAgent, the other is viewport You can set width(width), height(height) , Screen scaling (deviceScaleFactor), Whether it is a mobile terminal (isMobile), Whether there is a touch event (hasTouch).

const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iPhone = devices['iPhone 6'];

puppeteer.launch().then(async browser => {
  const page = await browser.newPage();
  await page.emulate(iPhone);
  await page.goto('https://www.example.com');
  // other actions...
  await browser.close();
});
Copy after login

The above code simulates iPhone6 visiting a website, where devices is the simulation parameters of some common devices built into puppeteer.

Many web pages require login. There are two solutions:

  • Let the puppeteer enter the account password. Common methods: click to use the page.click(selector[, options]) method, You can also choose to focus page.focus(selector). For input, you can use page.type(selector, text[, options]) to enter the specified string, and you can also set the delay in options to make the input slower and more like a real person. You can also use keyboard.down(key[, options]) to enter character by character.
  • If you use cookies to determine the login status, you can use page.setCookie(...cookies). If you want to maintain cookies, you can visit regularly.

#Tip: Some websites need to scan codes, but other webpages with the same domain name are logged in. You can try to log in to the webpage where you can log in and use cookies to access the jump. Scan the code.

For more powerful functions, please refer to the official documentation: https://zhaoqize.github.io/puppeteer-api-zh_CN/#/

More nodes For related knowledge, please visit: nodejs tutorial! !

The above is the detailed content of A brief analysis of how to use the Puppeteer library in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

See all articles