lonix
lonix

Reputation: 21011

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?

Upvotes: 1

Views: 7003

Answers (3)

Singh
Singh

Reputation: 120

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/")

Upvotes: 4

Carlos Iglesias
Carlos Iglesias

Reputation: 115

  • Launch create a new Process. Sometimes it is a limitation on your environments.
  • There are external services like browserstack.com that offers connecting to them, keeping very light your Tests, parallelization, and other advantages of this client/server design.

Upvotes: 1

Tang Chee Ming
Tang Chee Ming

Reputation: 21

I'm using another way to get Playwright to run on my existing browser using python.

import os
from playwright.sync_api import sync_playwright

def start_my_browser():
    custom_exe_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    if not os.path.exists(custom_exe_path):
    raise FileExistsError("Chrome not found {}, please install Chrome first".format(custom_exe_path))

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=500, executable_path=custom_exe_path)
        
        page = browser.new_page()
        page.goto("http://playwright.dev")
        print(page.title())
    browser.close()

Search for very long how to get Playwright "fire up" my existing browser as the docs in Playwright website didn't really explain much until I saw a video on China website explaining using the "executable_path" to run.

Upvotes: 1

Related Questions