Developer Snippet Diary

Authentication

Authentication is used to store login data to a file and then reuse it  https://playwright.dev/python/docs/auth

 context.storage_state(path=auth_file) # store files to authentication

1. saveauth.py and run this file to save auth

from playwright.sync_api import sync_playwright
import os

def setup_auth():
    with sync_playwright() as p:
        browser = p.chromium.launch( headless=False)
        context = browser.new_context()
        page = context.new_page()
        page.goto('https://github.com/login') # Navigate to GitHub login

        # Interact with login form
        page.get_by_label("Username or email address").fill("RizwanKMW")
        page.get_by_label("Password").fill("Password here")
        page.get_by_role("button", name="Sign in", exact=True).click()

        # Wait for navigation to complete
        page.wait_for_url('https://github.com/')

        # Define and check auth directory
        auth_dir = 'auth/.auth'
        auth_file = os.path.join(auth_dir, 'github-auth.json')
        
        # Verify directory exists and is writable
        if not os.path.exists(auth_dir):
            print(f"Creating directory: {auth_dir}")
            os.makedirs(auth_dir)
        else:
            print(f"Directory already exists: {auth_dir}")
            
        # Check if we have write permissions
        if not os.access(auth_dir, os.W_OK):
            raise PermissionError(f"No write permission for directory: {auth_dir}")
            
        print(f"Attempting to save state to: {os.path.abspath(auth_file)}")
        
        # Save the authenticated state
        context.storage_state(path=auth_file)
        
        print("Authentication state saved successfully")
        browser.close()

if __name__ == '__main__':
    setup_auth()

2. reuse auth

from playwright.sync_api import sync_playwright
import os
import time

def verify_auth_state():
    # Path to your saved auth state
    auth_file = 'auth/.auth/github-auth.json'
    
    # Verify auth file exists
    if not os.path.exists(auth_file):
        print(f"Authentication state file not found at: {os.path.abspath(auth_file)}")
        print("Please run setup_auth.py first")
        return

    try:
        with sync_playwright() as p:
            # Launch browser in non-headless mode with saved state
            print(f"Loading authentication state from: {os.path.abspath(auth_file)}")
            browser = p.chromium.launch(headless=False, slow_mo=500)  # slow_mo adds delay for visibility
            context = browser.new_context(storage_state=auth_file)
            page = context.new_page()

            # Go to a protected GitHub page
            print("Navigating to GitHub settings page...")
            page.goto('https://github.com/settings/profile')
            
            # Print current URL to verify where we landed
            print(f"Current URL: {page.url}")
            
            # Check if we're logged in by looking for profile elements
            try:
                profile_header= page.locator("textarea[class='form-control form-control user-profile-bio-field js-length-limited-input']")
                if profile_header.is_visible(timeout=10000):
                    print("Successfully authenticated - Profile page visible")
                    profile_header.fill("Zindgi dii chass lay gay o")
                else:
                    print("Authentication might have failed - Profile header not found")
            except Exception as e:
                print(f"Error checking profile header: {str(e)}")
                print(f"Page content preview: {page.content()[:500]}...")

            # Keep browser open for manual inspection
            print("Browser will remain open for 60 seconds. Interact with it manually if needed.")
            time.sleep(60)  # Keeps browser open for 60 seconds
            input()
            # You can uncomment below to keep it open indefinitely until you close it manually
            # input("Press Enter to close the browser...")

            browser.close()
            print("Browser closed")

    except Exception as e:
        print(f"Error occurred: {str(e)}")

if __name__ == '__main__':
    verify_auth_state()
Posted by: R GONDAL
Email: rizikmw@gmail.com