search
HomeWeb Front-endJS TutorialA brief analysis of how to use the Puppeteer library in 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

or

yarn add puppeteer

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()

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();

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() //点击搜索按钮

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();
});

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)