For the complete documentation index, see llms.txt. This page is also available as Markdown.

优化流量

了解在使用 Playwright 和 Puppeteer 时优化 无头浏览器 流量的关键策略

你的自动化脚本经常会下载不必要的资源,例如图片、样式表、字体和其他媒体文件。这些文件会消耗带宽,并可能拖慢你的爬取操作。

你可以完全阻止这些不必要的资源加载。通过拦截网络请求并有选择地屏蔽媒体文件,你可以只关注真正需要的数据。

这些代码片段同时适用于 Playwright 和 Puppeteer,可在媒体资源下载前将其阻止:

async def block_resources(route):
    request = route.request
    resource_type = request.resource_type
    if resource_type in ['image', 'stylesheet', 'media', 'font']:
        await route.abort()
    else:
        await route.continue_()
await page.route('**/*', block_resources)

这有帮助吗?