Playwright 添加cookies

同selenium一样,在测试过程中想绕过登录直接添加cookies登录,查看官方文档:

一、获取cookies


image.png

二、添加cookies

image.png

第一步手动登录成功后保存cookies

    from playwright.sync_api import Playwright, sync_playwright, expect

    def run(playwright: Playwright) -> None:
        browser = playwright.chromium.launch(headless=True)
        context = browser.new_context()

        # Open new page
        page = context.new_page()

        # Go to https://www.baidu.com/
        page.goto("https://www.baidu.com/")

        #判断登录成功后获取cookies
        cookies = context.cookies()

        print("cookies",cookies)
        # Close page
        page.close()

        # ---------------------
        context.close()
        browser.close()


    with sync_playwright() as playwright:
        run(playwright)

下次登录时,直接为浏览器添加cookies,保存登录状态

from playwright.sync_api import Playwright, sync_playwright, expect
import time
def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    # Open new page
    page = context.new_page()

    # Go to https://www.baidu.com/
    page.goto("https://creator.douyin.com/")

   cookies = []
    #设置cookies
    context.add_cookies(cookies)
    page.goto("https://creator.douyin.com/creator-micro/home")
    #等待成功登录的页面出现
    page.wait_for_url('https://creator.douyin.com/creator-micro/home')

    # Close page
    page.close()

    # ---------------------
    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

你可能感兴趣的:(Playwright 添加cookies)