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?

alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
Jack
  • 497
  • 3
  • 9
  • 21
  • 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. – alecxe Aug 06 '14 at 04: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 – Jack Aug 07 '14 at 02:29

2 Answers2

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
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
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.

Community
  • 1
  • 1
WeaselFox
  • 7,100
  • 7
  • 42
  • 73