前言

大部分网站保存登录状态是用cookies,也有个别网站是在请求头部添加token实现保存登录。
playwright 可以使用set_extra_http_headers() 方法设置浏览器请求头部参数

设置头部参数headers, 字典键值对

from playwright.sync_api import sync_playwright, expect
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/


with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()

    # 设置请求头部(仅供参考示例)
    page.set_extra_http_headers(
        headers={
            "Authorization": "Bearer ****************************"
        }
    )

也可以在context 上下文添加头部参数

from playwright.sync_api import sync_playwright, expect
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/


with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context()
    # 设置请求头部
    context.set_extra_http_headers(
        headers={
            "Authorization": "Bearer *****************"
        }
    )
    page = context.new_page()

文章转自:https://www.cnblogs.com/yoyoketang/p/17642942.html