<>Puppeteer拦截器在数据抓取中的使用

Puppeteer提供的拦截器功能可以用来拦截请求,当访问页面时可以拦截无用请求,加快请求速度。

<>拦截器使用示例

下面是Puppeteer Api文档中关于拦截器的一个例子,下面针对这个例子说明相关问题及使用注意点。
const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser
=> { const page = await browser.newPage(); await page.setRequestInterception(
true); page.on('request', interceptedRequest => { if (interceptedRequest.url().
endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))
interceptedRequest.abort(); else interceptedRequest.continue(); }); await page.
goto('https://example.com'); await browser.close(); });
拦截功能的使用需要在无头模式下才会生效,因此需要在启动的时候设置。
puppeteer.launch({ headless: true, options: ['--proxy-server=' + proxy] });

启动后设置启用拦截,随后对request事件监听。由于在请求发出前,就已经添加了要拦截的url,因此为了变更拦截参数,可以考虑拦截参数从配置中心读取或每次从请求参数中读取要拦截的请求。
page.setRequestInterception(true); page.on('request', interceptedRequest => {
...... }
若对请求拦截调用
interceptedRequest.abort();
若放行请求则调用
interceptedRequest.continue();
<>拦截过程中两个重要的方法

interceptedRequest.continue([overrides]);
interceptedRequest.respond(response);

这个两个方法很有意思,先看continue方法API定义。

continue方法定义

request.continue([overrides])
overrides Optional request overwrites, which can be one of the following:
url If set, the request url will be changed
method If set changes the request method (e.g. GET or POST)
postData If set changes the post data of request
headers If set changes the request HTTP headers

通过定义,我们能够对请求进行篡改,然后将篡改的请求发向目标。
interceptedRequest.continue({ postData: postData.replace("keyword=", "keyword="
+ keyword) + "&currPage=" + p });
respond方法定义

request.respond(response)
response Response that will fulfill this request
status Response status code, defaults to 200.
headers Optional response headers
contentType If set, equals to setting Content-Type response header
body <Buffer|string> Optional response body
returns:


有时整个请求结果必须用到某个子请求的响应,这时候我们可以使用request.respond(response)方法,可以实现快速返回的效果。例如请求某个链接,响应时间过长,我们可以利用这个方法快速返回一个兜底数据。加快整体请求过程。
await page.setRequestInterception(true); page.on('request', request => {
request.respond({ status: 404, contentType: 'text/plain', body: 'Not Found!' });
});
<>小结

通过拦截器的功能及相关方法,可以加快请求、篡改数据、返回兜底结果,最终加快数据抓取或自动化测试的过程

<>参考

[1] puppeteer api doc,

https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#requestrespondresponse

<https://github.com/GoogleChrome/puppeteer/blob/v1.8.0/docs/api.md#requestrespondresponse>

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信