You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright Python中传递全部HTTP请求头?

在Playwright Python中自定义所有请求头信息

1. 全局设置通用请求头

Playwright Python支持在创建浏览器上下文时,通过extra_http_headers参数一次性传入所有需要的请求头(比如accept、accept_encoding、accept_language、referer等)。这个设置会对该上下文下的所有页面请求生效,和你已使用的user_agent参数完全兼容。

修改你现有代码中的上下文创建逻辑:

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    # 定义需要的额外请求头
    custom_headers = {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "accept_encoding": "gzip, deflate, br",
        "accept_language": "zh-CN,zh;q=0.9,en;q=0.8",
        "referer": "https://www.some-referer.com/"
    }
    context = browser.new_context(
        user_agent=agent,
        extra_http_headers=custom_headers  # 新增全局请求头配置
    )
    page = context.new_page()
    response = page.goto("https://www.somewebsite.com/")

    # 后续页面操作保持不变
    page.locator('#some_id').fill("some_text")
    page.press('#another_id', "Enter")

    page.route("**/*", intercept_route)

2. 设置Cookies

Cookies无法通过extra_http_headers传递,需要单独使用context.add_cookies()方法添加,示例如下:

# 在创建页面之前添加目标站点的Cookies
context.add_cookies([
    {
        "name": "session_id",
        "value": "your_session_value",
        "domain": ".somewebsite.com",
        "path": "/",
        "expires": -1  # 会话级Cookie,关闭浏览器后失效
    },
    {
        "name": "user_preference",
        "value": "dark_mode",
        "domain": ".somewebsite.com",
        "path": "/"
    }
])

3. 动态修改单个请求的头(可选)

如果需要针对特定请求单独调整头信息,可以在你的intercept_route拦截函数中修改:

def intercept_route(route):
    # 获取当前请求的原始头信息
    current_headers = route.request.headers
    # 修改或新增自定义头
    current_headers["x-custom-token"] = "your-token"
    # 携带修改后的头继续请求
    route.continue_(headers=current_headers)

以上方式就能覆盖你需要的所有请求头、Cookies等自定义配置需求。

内容的提问来源于stack exchange,提问作者NewbieProgrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:35:47