Python Selenium Webdriver - 尝试除循环

时间:2014-03-30 07:50:00

标签: python selenium try-except

我试图在逐帧加载的网页上自动化流程。我试图建立一个try-except循环,只有在确认元素存在后才会执行。这是我设置的代码:

from selenium.common.exceptions import NoSuchElementException

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

以上代码不起作用,而以下天真的方法确实如此:

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

上面的try-except循环中是否有任何遗漏?我尝试了各种组合,包括在try之前而不是在except之后使用time.sleep()。

由于

2 个答案:

答案 0 :(得分:23)

您具体问题的答案是:

from selenium.common.exceptions import NoSuchElementException

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

但是,有一种更好的方法可以等到元素出现在页面上:waits

答案 1 :(得分:3)

另一种方式可能是。

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

在WebDriverWait调用中,将驱动程序变量和秒等待。