How to save and load cookies in Playwright?

You can save and load cookies in Playwright by making use of the cookies() and add_cookies() methods of the browser context. The former returns the current cookies whereas the latter helps you add new cookies and/or overwrite the old ones.

Here is some sample code for saving and loading the cookies in Playwright while browsing the ScrapingBee website:

import json
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless = False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://scrapingbee.com")
    
    # Save the cookies
    with open("cookies.json", "w") as f:
        f.write(json.dumps(context.cookies()))

    # Load the cookies
    with open("cookies.json", "r") as f:
        cookies = json.loads(f.read())
        context.add_cookies(cookies)

Related Playwright web scraping questions: