Python Selenium Webdriver - Try except loop

前端 未结 2 1707
小蘑菇
小蘑菇 2021-02-07 13:51

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

相关标签:
2条回答
  • 2021-02-07 14:24

    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

    0 讨论(0)
  • 2021-02-07 14:30

    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.

    0 讨论(0)
提交回复
热议问题