Search code examples
c#playwrightplaywright-dotnet

Connecting to an existing browser using Playwright


I'm using Playwright in "library mode". The typical approach is: create Playwright instance, launch browser, create context, create page, go to URL.

But there are also ConnectAsync and ConnectOverCDPAsync which allow connection to an existing browser.

When would I do that? The docs don't explain in which cases I need to connect to an existing browser rather than doing it the way shown in the "getting started" docs? Do I get extra functionality when connecting to an existing browser?


Solution

  • I use an existing browser session and connect playwright library with it. I use it for scraping, sometimes I have to manually change some setting in the browser, leave it open and then run my playwright script which then takes over the existing browser session.

    I first start a chrome browser with a batch file

    cd C:\Program Files\Google\Chrome\Application
    chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\Users\Demo\chromepythondebug"
    

    and then add connect playwright with the chrome browser session

    from playwright.sync_api import sync_playwright, Playwright
    
    playwright = sync_playwright().start()
    
    chromium = playwright.chromium
    browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
    default_context = browser.contexts[0]
    page = default_context.pages[0]
    page.goto("https://www.google.com/")