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!
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/#/
- 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()
// 获取页面内容 //$$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();
// 通过表单输入进行搜索 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() //点击搜索按钮
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!

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
