Puppeteer allows blocking any outgoing requests while loading the page. Whether you want to block ads, tracking scripts, or different types of resources, it is relatively easy to do with Puppeteer.
If you want to speed up scrapping or make screenshots faster, you can disable all the requests that do not make any crucial impact on the results.
Puppeteer allows blocking any outgoing requests while loading the page. Whether you want to block ads, tracking scripts, or different types of resources, it is relatively easy to do with Puppeteer.
A full example of blocking requests
Let’s start with a fully working example on how to intercept and block requests in Puppeteer:
The result is:
Sorry, but I won’t show you the resulting screenshot of the site because it looks awful without CSS and JS.
A step-by-step explanation
The most crucial step is not to forget to enable request interception before sending any request:
Otherwise, the trick won’t work.
After request interception is enabled, you can listen to any new outgoing request while the page is being loaded and decide on a per-request basis whether to block the request or not.
If you want to block all requests to www.google-analytics.com to speed up the site loading and to avoid tracking, then just filter requests based on the domain substring:
The better option is to parse URL, extract domain, and filter based on the domain name:
Because you might have an URL that accidentally might include www.google-analytics.com.
Blocking requests by resource type
If you need to block a set of requests by the resource type, like images or stylesheets, regardless of the extension and URL pattern, you can use the request.resourceType() method to test against blocking resource type:
The result is the same as for the initial example:
Puppetteer supports blocking the next resource types:
document
stylesheet
image
media
font
script
texttrack
xhr
fetch
eventsource
websocket
manifest
other
As you see, it is pretty straightforward.
Block images
Disabling image loading dramatically improves the loading time of the page and speeds ups the rendering process.
You can block (disable) images in Puppeteer by blocking requests with resource type image.
It is no different from blocking any other resource type:
You can see from the logs that it works:
The result without images:
And compare it to the original rendering:
Also, I would consider blocking media, fonts, and stylesheets if your goal is not to take screenshots of the page but to crawl.