I am looking for a way to use Selenium WebDriver to interact with a browser session that I’ve already opened manually. Usually, Selenium starts a fresh instance with a clean profile, but I need to perform automation on a page where I’ve already logged in and bypassed complex MFA. Can I use the remote debugging port or a specific set of ChromeOptions to attach my script to this existing session without the driver closing the window?
3 answers
Yes, this is entirely possible, primarily with Chromium-based browsers like Chrome and Edge. You must first launch your browser manually via the command line with a specific flag: --remote-debugging-port=9222. This opens a communication channel that Selenium can tap into. In your script, you then configure your ChromeOptions by calling options.add_experimental_option("debuggerAddress", "127.0.0.1:9222"). When you initialize the WebDriver with these options, it will attach to the open window instead of launching a new one. This is a game-changer for scraping sites with complex login flows or for testing specific states in a long web form without re-running the entire script. Just ensure all other Chrome instances are closed before you start the debug session to avoid port conflicts.
Does this method work consistently across different operating systems, or are there specific permission issues I should be aware of when launching Chrome from the terminal on macOS versus Windows? I've noticed that sometimes the port is refused if the browser wasn't started with the correct user profile path.
You need the --remote-debugging-port flag. Once the browser is up, set the debuggerAddress in your Selenium options to match that port, and the driver will hook right in.
I agree with Christina. I use this daily for debugging. It saves so much time because you can manually navigate to the exact part of the app that’s failing and then trigger your script to see exactly how the WebDriver interacts with the elements in real-time.
Gregory, on macOS, you usually have to point directly to the binary within the .app package in your terminal. A common fix for the port refusal is adding the --user-data-dir flag along with the port flag. This points the "debug" instance to a temporary folder so it doesn't collide with your main personal Chrome profile. If you don't specify a data directory, Chrome might just try to open a new tab in your existing non-debug window, which Selenium won't be able to see or control.