Search code examples
pythonseleniumselenium-webdriverelementrestart

Selenium Python- If cannot find element, close everything and restart


element = driver.find_element_by_id("user_first_name")

If python cant find the element in the page, what do I add to the code to close the browser/ program and restart everything?


Solution

  • You can use WebdriverWait and wait until the element can be found, or timeout occurred:

    from selenium.common.exceptions import TimeoutException
    from selenium.webdriver.support.ui import WebDriverWait
    
    try:
        element = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id('user_first_name'))
        # do smth with the found element
    except TimeoutException:
        print "Element Not Found"
        driver.close()
    

    Another option would be to put the whole opening the browser, getting the page, finding element into a endless while loop from which you would break if element is found:

    from selenium import webdriver
    from selenium.common.exceptions import NoSuchElementException
    
    while True:
        driver = webdriver.Firefox()
        driver.get('http://example.com')
    
        try:
            element = driver.find_element_by_id("user_first_name")
        except NoSuchElementException:
            driver.close()
            continue
        else:
            break
    
    # do smth with the element