Python selenium keep browser open
Asked Answered
A

4

51

I am using selenium to open some browser windows for marketing reasons. I simply open my marketing sources, login via selenium and start working.

The problem is, that after the code is executed selenium closes the window.

All solutions havent helped much so far.

I have 13 browser windows atm., which look like this:

def open_instagram():    
    try:
        # Connect
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--incognito")
        browser = webdriver.Chrome('drivers/chromedriver.exe', chrome_options=chrome_options)
        browser.set_window_size(1800, 900)
        browser.get("https://www.instagram.com/accounts/login/?hl=de")
        browser.find_element(By.NAME, 'username').send_keys('MYEMAIL', Keys.TAB, 'MYPW', Keys.ENTER)
    except Exception as e:
        print (e, 'Instagram')

open_instagram()

The closest solution which I found is adding this at the end of my script, but somehow it will only keep 5 windows open, than close 5 windows and open next 5 new windows:

while True:
    pass

I just want that selenium keeps all browser windows open, until I close them manually.

Aubergine answered 15/8, 2018 at 19:38 Comment(2)
If you need this to hand-weave scraping code, you'll have better results with an interactive session: you'll be able to interact with the browser both by hand (to get XPaths, ids and such) and with commands.Precede
How's that @ivan_pozdeev, how do I create an interactive session?Lemar
W
87

If you want chrome and chromedriver to stay open, you have to use the 'detach' option when starting chromedriver.

In your case add :

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

before you pass in the options to the browser

browser = webdriver.Chrome('drivers/chromedriver.exe', options=chrome_options)

Or you can run the code in debug mode with breakpoint at the end and when it pauses 'kill' the program and take over the browser if you want to, but this works in IDE only.

Update: As of Jan. 24, chrome_options parameter when initializing Webdriver is now only "options".

Whitehorse answered 15/8, 2018 at 20:28 Comment(6)
You also need from "selenium.webdriver.chrome.options import Options"Carpel
Is it possible to reuse this browser window? E.g. get the PID or something and use explicitly if exists?Vibrate
With Python you use chrome_options.add_experimental_option("detach", True), with C# you use the ChromeOptions.LeaveBrowserOpen property... either way tho neither of them will function until you add options.AddExcludedArgument("enable-automation") to your options setup.Hindenburg
("detach", True) option only works on terminal. It doesn't work when debugging in VSCodeBirthroot
To exclude enable-automation (that hides the "Chrome is being controlled by automated software banner" banner, and maybe does other things, but does not actually disable automation) in Python, use chromeOptions.add_experimental_option("excludeSwitches", ["enable-automation"])Roseannaroseanne
'chrome_options' is deprecated, use 'options' instead like so: browser = webdriver.Chrome('drivers/chromedriver.exe', options=chrome_options)Jemena
H
8

You can also add global browser like so:

def open_instagram():    
    try:
        # Connect
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--incognito")
        global browser # this will prevent the browser variable from being garbage collected
        browser = webdriver.Chrome('drivers/chromedriver.exe', chrome_options=chrome_options)
        browser.set_window_size(1800, 900)
        browser.get("https://www.instagram.com/accounts/login/?hl=de")
        browser.find_element(By.NAME, 'username').send_keys('MYEMAIL', Keys.TAB, 'MYPW', Keys.ENTER)
    except Exception as e:
        print (e, 'Instagram')

open_instagram()

Source

Halcyon answered 24/9, 2019 at 14:52 Comment(0)
I
4

The simplest way to do this would be just to add input() after your get function. This will prompt you to have to press the Enter key to continue and will thus keep your program from finishing. It might work more considering you seem to be manually shifting through each webpage? Alternatively you can stop it from closing using the time.sleep function in the time module, but that isn't efficient for keeping it open indefinitely.

Illnatured answered 29/12, 2022 at 9:57 Comment(0)
H
-1

Selenium 4 / PHP / Docker

$this->driver = RemoteWebDriver::createBySessionID(self::$session_id, self::$server, 60000, 60000);

version: "3.5"
#Latest version
networks:
  grid-network:

services:

  selenium-hub:
    image: selenium/hub:latest
    container_name: selenium-hub
    ports:
      - "4446:4444"
    networks:
      - grid-network
      
  chrome:
    shm_size: 4gb 
    image: selenium/standalone-chrome:latest
    container_name: chrome
    depends_on:
      - selenium-hub
    environment:
      - NODE_MAX_SESSION=5
      - NODE_MAX_INSTANCES=5
      - GRID_MAX_SESSION=31556926
      - GRID_BROWSER_TIMEOUT=31556926
      - GRID_TIMEOUT=31556926
      - GRID_SESSION_TIMEOUT=31556926
      - SESSION_TIMEOUT=31556926
      - NODE_SESSION_TIMEOUT=31556926
      - GRID_CLEAN_UP_CYCLE=31556926
      - SE_NODE_SESSION_TIMEOUT=31556926
      - SE_SESSION_REQUEST_TIMEOUT=31556926
    volumes:
      - /dev/shm:/dev/shm
    ports:
      - "33333:5900"
      - "3333:7900"
      - "44444:4444"
    links:
      - selenium-hub
    networks:
      - grid-network
Histo answered 28/1, 2022 at 15:3 Comment(1)
This is just code with no explanation whatsoeverSanctitude

© 2022 - 2024 — McMap. All rights reserved.