Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium Webdriver - Try except loop

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

like image 722
user3294195 Avatar asked Mar 30 '14 07:03

user3294195


People also ask

How does Python handle timeout exception in selenium?

If one of them is hidden, and Selenium is interacting with that element, then there is a chance that Selenium will not be able to return it. You can try using some other property to locate the element such as CSS Selector or Xpath . Use explicit waits. This will ensure all timeouts happen after the given time.


2 Answers

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

like image 61
neoascetic Avatar answered Oct 24 '22 15:10

neoascetic


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.

like image 29
Charls Avatar answered Oct 24 '22 14:10

Charls