Hello,
I am trying to disconnect the chrome web driver from the chrome browser session.
After I close the terminal that ran the code, the browser closes.
My code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service asChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support importexpected_conditions as EC
import os
import subprocess
def open_chrome_browser(urls):
try:
user_name = os.getlogin().lower()
options = webdriver.ChromeOptions() # initiates ChromeOptions so the options are attached to the chromedriver
options.add_experimental_option("detach", True) # allows for the browser to disconnect the chromedriver
# and remain open.
options.add_argument(rf"user-data-dir=C:\\Users\\{user_name}\\AppData\\Local\\Google\\Chrome\\User Data") # adds the Default Chrome Profile location
options.add_argument(r"--profile-directory=Default")# uses the Default Chrome profile for the chromedriver
options.add_argument('log-level=3') # sets log level to 3 insted of 0 to accomodate for AWS connection
options.add_argument("--disable-infobars") # Disables the "Chrome is being controlled" message
options.add_experimental_option("excludeSwitches", ["enable-automation"]) # Removes the automation flag
options.add_experimental_option('useAutomationExtension', False) # Ensures the extension is not used
#specify path to the chromedriver executable
chrome_driver_path = rf'C:\\Users\\{user_name}\\invoke_processes\\SDA_Tool\\selenium\\chromedriver\\win64\\126.0.6478.126\\chromedriver.exe'
service = ChromeService(executable_path=chrome_driver_path)
driver = webdriver.Chrome(options=options)
driver.get(urls[0])
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'body')) # Wait until the body tag is present
)
for url in urls[1:]:
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[-1])
driver.get(url)
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'body')) # Wait until the body tag is present
)
#detach the Webdriver from the browser
#Optionally, kill the ChromeDriver process if it was started with subprocess
#subprocess.Popen([chrome_driver_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE).terminate()
# optional Wait for a few seconds to ensure the page is fully loaded
#time.sleep(2)
except Exception as e:
print(f'Error occuured: {e}')
Selenium version 4.19
Using google website
chrome browser version 126.0.6478.127
Chrome driver version 126.0.6478.126
Windows 10 version 22H2 build 19045.4529