Python Selenium Webdriver - Try except loop

梦想与她 提交于 2019-12-20 18:32:26

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/22741591/python-selenium-webdriver-try-except-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!