18

I'm trying to automate processes on a webpage that loads frame by frame. I'm trying to set up a try-except loop which executes only after an element is confirmed present. This is the code I've set up:

from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        link = driver.find_element_by_xpath(linkAddress)
    except NoSuchElementException:
        time.sleep(2)

The above code does not work, while the following naive approach does:

time.sleep(2)
link = driver.find_element_by_xpath(linkAddress)

Is there anything missing in the above try-except loop? I've tried various combinations, including using time.sleep() before try rather than after except.

Thanks

user3294195
  • 1,748
  • 1
  • 19
  • 36
  • Your current code only sleeps if the element is not found. –  Mar 30 '14 at 07:55
  • Yes, the idea is that it waits 2 seconds before trying again, unless there's something wrong in the implementation? – user3294195 Mar 30 '14 at 07:57
  • I think I was confused by the wording of "executes after an element is confirmed present". My previous comment was an error. –  Mar 30 '14 at 07:58
  • Are you sure that the exception that you would expect it to throw is occurring in the `try` block? – anon582847382 Mar 30 '14 at 07:59
  • Yes. However, I've also tried `except` without explicitly referencing the exception. Still doesn't work... – user3294195 Mar 30 '14 at 08:01

2 Answers2

35

The answer on your specific question is:

from selenium.common.exceptions import NoSuchElementException

link = None
while not link:
    try:
        link = driver.find_element_by_xpath(linkAddress)
    except NoSuchElementException:
        time.sleep(2)

However, there is a better way to wait until element appears on a page: waits

neoascetic
  • 2,476
  • 25
  • 34
8

Another way could be.

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

try:
    element = WebDriverWait(driver, 2).until(
            EC.presence_of_element_located((By.XPATH, linkAddress))
    )
except TimeoutException as ex:
            print ex.message

Inside the WebDriverWait call, put the driver variable and seconds to wait.

Charls
  • 81
  • 1
  • 2
  • This does not work for me. Error message: `NameError: global name 'TimeoutException' is not defined`. I think for this example to work you'd at least need to `import selenium` and then replace line 5 by `except selenium.common.exceptions.TimeoutException as ex:`. – altabq Feb 02 '16 at 09:52
  • yes, you need. from selenium.common.exceptions import TimeoutException – Charls Feb 03 '16 at 16:59