如何在Playwright中仅为HTML文档设置自定义请求头?
仅为HTML文档添加自定义请求头(Playwright)
要实现只为HTML文档单独添加自定义请求头,你可以通过路由拦截精准控制请求,而非使用全局的browserContext.setExtraHTTPHeaders或page.setExtraHTTPHeaders。核心思路是拦截所有请求,判断资源类型为HTML文档时追加自定义请求头,其他请求保持原样放行。
JavaScript/TypeScript 示例
const { chromium } = require('playwright'); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); // 拦截所有请求,仅为HTML文档添加自定义头 await page.route('**/*', async (route) => { const request = route.request(); // 判断当前请求是否为HTML文档(resourceType为document) if (request.resourceType() === 'document') { // 合并原有请求头与自定义头,避免覆盖默认必要头 const updatedHeaders = { ...request.headers(), 'X-Custom-Identifier': 'your-special-token' // 替换为你的自定义标识头 }; await route.continue({ headers: updatedHeaders }); } else { // 非HTML文档请求直接放行 await route.continue(); } }); await page.goto('https://example.com'); // 后续业务操作 await browser.close(); })();
Python 示例
from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() # 定义路由处理逻辑 def handle_route(route): request = route.request if request.resource_type == "document": # 合并原有请求头和自定义头 updated_headers = {**request.headers, "X-Custom-Identifier": "your-special-token"} route.continue_(headers=updated_headers) else: route.continue_() page.route("**/*", handle_route) page.goto("https://example.com") # 后续业务操作 browser.close()
关键说明
- 通过
request.resourceType()(JS/TS)或request.resource_type(Python)判断资源类型,document对应HTML文档请求; - 合并原有请求头再添加自定义头,避免覆盖
User-Agent、Accept等默认必要请求头; - 路由拦截支持更精准的匹配规则(比如特定域名、URL前缀),灵活度远超全局请求头设置。
内容的提问来源于stack exchange,提问作者hao qian
相关产品推荐
相关产品推荐

