欢迎光临散文网 会员登陆 & 注册

puppeteer 使用体验

2023-05-04 21:46 作者:小老虎Tigger  | 我要投稿

puppeteer 其实已经用过很多次了,记录一下使用的一些体会。

首先它的功能和名称非常匹配,puppeteer是一个Node.js的一个库,它可以使我们在node中使用js代码来控制一个chromium浏览器。我们的一些手动的操作基本都能通过puppeteer来实现,所以puppeteer通常也被用来做自动化测试。由于puppeteer是直接操作的浏览器,所以更容易实现一些爬虫的功能(不会涉及cookie、跨域等问题)。

puppeteer的API非常清晰 https://pptr.dev/api

我们如果需要访问一个网站,通常需要以下的步骤来实现,可以看到代码层面和我们日常的操作逻辑非常相似。


我们如果想要操作、获取网页中的一些内容,puppeteer的API设计也和dom的API非常相似。

如果想要操作dom节点,我们可以使用$、$$方法,类似于document.querySelector、document.querySelectorAll。但是我们需要注意的是$、$$返回的并不是dom节点,而是Promise<ElementHandle<NodeFor<Selector>> | null>。我们可以通过ElementHandle去执行一些click、focus、type等操作。puppeteer.elementhandle

Page.$() method

Runs document.querySelector within the page. If no element matches the selector, the return value resolves to null.

Page.$$() method

The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolves to [].


如果我们需要获取dom中的一些数据,需要使用$eval、$$eval。

Page.$eval() method

This method runs document.querySelector within the page and passes the result as the first argument to the pageFunction.

$eval函数的pageFunction相当于是在chromium浏览器中运行,然后将返回的结果提供给了我们的nodejs,不能直接将dom返回,因为nodejs中执行的代码没有办法保持对chromium浏览器中对象的引用,如果想要访问chromium页面中的对象、方法,都需要使用puppetter提供的API来操作。这种方式,有点类似于electron。


puppeteer还提供了非常多的功能,可以植入脚本,切换frame、截图、转换页面保存为PDF等等。我们在使用过程中,要简单理解puppetter的运行流程,我们的nodejs代码是运行在node中,而我们使用的puppetter,则是将一些代码通过puppetter运行在了chromium浏览器中,这两者是通过puppetter来桥接的。


puppeteer 使用体验的评论 (共 条)

分享到微博请遵守国家法律