Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart a selenium webdriver? (Python)

for one of my scripts, I need to restart a browser (chromeDriver) session at some random point.

I have tried to restart the webdriver in a test script without success.

def start_browser():
    driver.get('https://www.google.com/')
    time.sleep(1)

def close():   
    driver.quit()
    driver.get("http://www.google.com/")


for x in range (1,5):
    start_browser()
    time.sleep(5)
    close()
    time.sleep(5)

For some reason, the script does not start a new instance of the browser, instead it crashes. I think I am missing out some vital selenium command, but I could not find anything on the official page.

like image 462
HansDampf Avatar asked Nov 30 '25 13:11

HansDampf


1 Answers

The question is a bit old, but for anyone still asking As mentioned in a previous comment, you will need to reinitiate the driver. Sometimes this is the easier way to clear all the cookies and run a test.

Assuming the funcs that you gave are from a class with a driver attribute

def start_browser(self):
    self.driver.get('https://www.google.com/')
    time.sleep(1)

def close(self):   
    self.driver.quit()
    self.driver = webdriver.Chrome(*driver_params)
    self.driver.get("http://www.google.com/")


for x in range (1,5):
    start_browser()
    time.sleep(5)
    close()
    time.sleep(5)

This isn't how 1 would actually write it IMO, but the restarting of the browser works, it's also best to an incognito mode to the driver if you want all cookies to be cleared too.

like image 191
Manish Sigdel Avatar answered Dec 03 '25 15:12

Manish Sigdel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!