1

This is in the context of robot framework's playwright library, but I haven't had any responses from them. Hopefully some playwright experts can help me out.

I'm trying to connect to an existing and already opened browser with playwright. Following this tutorial, I got it to work with selenium, but not with playwright.

I believe I'm trying to replicate this server-client dynamic.

My steps are:

  1. Open a browser: could be manual (as in the selenium case) but I think with playwright it has to specifically be a playwright process / browser. Therefore I've gone with npx playwright launch-server --browser chromium (have also tried with npx playwright open <url>).
  2. I use the url output by launch-server (eg. ws://127.0.0.1:49216/4eed2730f31b8a5af258df739cc319fe) in my code to connect_to_browser() and seeing Successfully connected to browser. In this code snippet I open up a headless browser and can navigate, etc. In this step I have also tried mixing in a persistent context, based on this example but also no luck. At this point But at least at this point I have a browser up and running on my screen that appears to be connected to the playwright server at port 49216.
  3. I now want some other code to connect to and use this existing browser. So in this code I also use connect_to_browser() without any apparent issues but if I want to do anything in this snippet, I have to open up a new browser, rather than being able to use the existing browser.

If I compare the browser and context catalogs between the code in step 2 and 3, they do not match. It's like although both are connected via that ws url, they cannot talk to or know about each other?

Btw, also tried starting up the playwright library with playwright_process_port but I get RuntimeError: Could not connect to the playwright process.

JSalazAlt
  • 11
  • 3

1 Answers1

0

With Playwright it is possible to connect to a running Chromium-based browser using the Chrome DevTools Protocol (CDP).

Start the browser setting the remote debugging port:

chrome --remote-debugging-port=1243

Navigate to some page and then connect to the browser using the method connect_over_cdp (Playwright docs):

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
    chromium = playwright.chromium
    browser = chromium.connect_over_cdp('http://localhost:1243')
    context = browser.contexts[0]
    page = context.pages[0]
    # find an element and act on it
    
with sync_playwright() as playwright:
    run(playwright)

Just to clarify, playwright is a NodeJS library. There is a Python wrapper and also a Robot Framework wrapper, called Browser Library. The question and this answer refer to the Python wrapper.

At the time of writing the Browser library does not support this functionality, but it is planned. Monitor this issue to know when the feature has been implemented.

Marduk
  • 982
  • 8
  • 12