Closing Selenium webdriver after X seconds


I am using selenium webdriver (firefox) on Ubuntu + Python, and run into an issue where sometimes the page doesn’t load, and the whole script simply hangs.
Is there a way to force-exit the webdriver window after X seconds ?
Looking for code like the one below, that actually works though. It looks like if the webdriver is waiting on the response, it will wait (almost) indefinitely).

my_html = driver.page_source #get whatever we have after 5 sec
driver.close() #close driver

NOTE!: The accepted answer is correct. The issue was caused by my geckodriver being out of date (v 0.11 vs v.019).
To check your version on ubuntu:

geckodriver --version   #command in terminal

to update the driver (if needed), use these steps. Note – Sandeep’s answer worked best for me.

Asked By: FlyingZebra1



from selenium import webdriver
from time import sleep

record = ""
driver = webdriver.Firefox()
    my_html = driver.page_source #get whatever we have after 5 sec

Setting page load timeout, as described here, will achieve what you’re after. It will raise a TimeoutException if the page doesn’t load within the time given, closing the program.

Answered By: n1c9

When the page isn’t loading and and the whole script simply hangs the solution would be to configure set_page_load_timeout().

Here is an effective code block catching the TimeoutException. Irrespective of TimeoutException happening or not remember to call quit() method within try-except{} block to keep away the dangling instances of the WebDriver variants.

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome(executable_path=r'C:UtilityBrowserDriverschromedriver.exe')
try :
    print("URL successfully Accessed")
except TimeoutException:
    print("Page load Timeout Occured. Quiting !!!")
Answered By: undetected Selenium
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.