2
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?

2
  • Why do you need to restart the whole thing and check if element is there? Is it being showed randomly, or what is the reason? Thanks. Commented Aug 6, 2014 at 4:57
  • Thanks @alecxe The program runs on a loop an n number of times. When it couldn't locate an element, it raised an error and the whole loop stopped. I think reloading the page would work just fine.. rather than restarting the whole thing Commented Aug 7, 2014 at 2:29

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

If your'e waiting for an Ajax call to be completed you could use waitForElementPresent(locator). see this question for more options for handling the wait.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.