Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium Detach Option Not Working

I want to write a Python script using Selenium and Chrome where Selenium won't close the Chrome browser when the script finishes. From doing a bunch of googling, it looks like the standard solution is to use the detach option. But when I run the following script:

import selenium
from selenium import webdriver

from selenium.webdriver.chrome.options import Options
chrome_options = Options() 
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.google.com/")

It opens up Chrome, goes to Google's homepage, and then closes the browser. It's not throwing any errors.

Any idea why it's not working? I'm using the latest version of Google Chrome on Windows 10, and I've got the latest version of the selenium module installed. I couldn't find anything online that said the experimental detach option no longer existed. And I double checked the API, and it looks like it's the right syntax.

like image 407
Anders Schneiderman Avatar asked Sep 07 '25 22:09

Anders Schneiderman


1 Answers

I discovered another way to go: start Chrome in remote debugging mode, then connect to it. That way, not only does the browser stay open, but you can also use your existing Chrome profile so you can take advantage of any sites your cookies allow you to access without having to log in every time you run the script.

Here's what you need to do if you're on Windows 10:

  1. Start Google Chrome up remotely, pointed towards your existing user profile and the port you want to use:
cd "C:\Program Files (x86)\Google\Chrome\Application"
chrome.exe -remote-debugging-port=9014 --user-data-dir="%LOCALAPPDATA%\Google\Chrome\User Data"
  1. In your python script, connect to the local port that this version of Chrome is running on:
import selenium
from selenium import webdriver

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "localhost:9014")
driver = webdriver.Chrome(options=chrome_options)

driver.get("https://github.com/")
like image 62
Anders Schneiderman Avatar answered Sep 10 '25 18:09

Anders Schneiderman