美文网首页
Playwright 添加cookies

Playwright 添加cookies

作者: HC2 | 来源:发表于2022-09-20 18:44 被阅读0次
    同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

          本文链接:https://www.haomeiwen.com/subject/dilvortx.html