Last active
August 25, 2025 08:56
-
-
Save devinschumacher/bcf6b186206df9c47a3f484249005f59 to your computer and use it in GitHub Desktop.
how to save & reuse authentication / login state with playwright python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from playwright.sync_api import sync_playwright | |
| def setup_authentication(): | |
| with sync_playwright() as playwright: | |
| browser = playwright.firefox.launch(headless=False, slow_mo=500) | |
| context = browser.new_context() | |
| page = context.new_page() | |
| # insert logic for navigating to a login, auth, etc. | |
| # then pause to manually interact/login | |
| page.pause() | |
| # exit the pause properly by clicking the resume (play button) thing on the helper | |
| # Create the directory if it doesn't exist | |
| auth_dir = "playwright/.auth" | |
| os.makedirs(auth_dir, exist_ok=True) | |
| # save authentication state | |
| context.storage_state( | |
| path=os.path.join(auth_dir, "storage_state.json"), | |
| ) | |
| browser.close() | |
| # Call the function to run the setup | |
| setup_authentication() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # reuse state in a script | |
| from playwright.sync_api import sync_playwright | |
| with sync_playwright() as playwright: | |
| browser = playwright.chromium.launch(headless=False, slow_mo=500) | |
| context = browser.new_context( | |
| storage_state = "playwright/.auth/storage_state.json" | |
| ) | |
| page = context.new_page() | |
| # insert logic for doing stuff | |
| # you should be logged in already | |
| context.close() | |
| browser.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # reuse state w/ codegen (straight from terminal | |
| # playwright codegen --browser <browser> --load-storage=playwright/.auth/storage_state.json <destination-website> | |
| playwright codegen --browser firefox --load-storage=playwright/.auth/storage_state.json https://app.ahrefs.com |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment