Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python selenium keep browser open

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.

like image 988
Roman Avatar asked Aug 15 '18 19:08

Roman


People also ask

How do I keep a browser session alive in Selenium?

We can keep a session alive for long Selenium scripts in automation. In Chrome browser, this can be achieved with the help of the ChromeOptions and Capabilities classes. Capabilities class can get the capabilities of the browser by using the method – getCapabilities.

Can we use Selenium to work with an already open browser session?

We can connect to an already open browser using Selenium webdriver. This can be done using the Capabilities and ChromeOptions classes. The Capabilities class obtains the browser capabilities with the help of the getCapabilities method.

Can you use Selenium without opening browser Python?

We can perform Selenium testing without a browser. This is achieved by triggering the execution in a headless mode. The headless execution can decrease the utilization of key resources and is being adopted widely.


1 Answers

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)

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.

EDIT - added the import for clarity

like image 138
AnkDasCo Avatar answered Sep 21 '22 10:09

AnkDasCo