Search code examples
pythonplaywrightplaywright-python

How to connect to existing logged in chrome instance in Playwright on MacOs?


My goal is to automate a task on a website that requires login. So I want to login once manually and let the automation run from there. I tried using CRD but when my code runs, it opens a new window where my account is not logged in. Here is an example code I am running:

from playwright.sync_api import sync_playwright
import time


def connect_to_chrome_debugger():
    with sync_playwright() as p:
        # Connect to the running Chrome instance using CDP
        browser = p.chromium.connect_over_cdp("http://localhost:9234")

        # Create a new page in the connected browser
        page = browser.new_page()

        # Navigate to a URL
        page.goto("https://gmail.com")
        time.sleep(10)

        # Print the title of the page
        print(page.title())

        # Perform additional actions as needed

        # Close the page (not the entire browser)
        page.close()


if __name__ == "__main__":
    connect_to_chrome_debugger()

Now in this example, I have already logged into my gmail on chrome and when I launch the CRD session using:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9234

it shows me as logged in user. However, when playwright runs and opens a new window, then it behaves as if I am logged out.


Solution

  • The issue Playwright created a new browser context when connecting to the Chrome instance running via CDP. This new context doesn't share the session data (cookies, local storage, etc.) with the existing tabs.

    How you can address this:

    1. User the Same Browser Context

    When connecting via CDP, ensure that you interact with the existing tabs and not create a new one. Modify the code to reuse the existing page:

    from playwright.sync_api import sync_playwright
    import time
    
    def connect_to_chrome_debugger():
        with sync_playwright() as p:
            # Connect to the running Chrome 
            browser = p.chromium.connect_over_cdp("http://localhost:9234")
            
            context = browser.contexts[0]
            page = context.pages[0]  # Assuming you want the first tab, adjust as needed
    
            # Navigate to a URL 
            page.goto("https://gmail.com")
            time.sleep(10)
        
            print(page.title())
    
            # Close the page 
            page.close()
    
    if __name__ == "__main__":
        connect_to_chrome_debugger()
    

    2. Use User Data Directory

    userDataDir for Chrome when launching it for remote debugging.

    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9234 --user-data-dir="/path/to/your/profile"