17

我正在尝试使逐帧加载的网页上的流程自动化。我正在尝试设置一个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 循环中是否缺少任何内容?我尝试了各种组合,包括使用 time.sleep() beforetry而不是 after except

谢谢

4

2 回答 2

33

您的具体问题的答案是:

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

于 2014-03-30T08:05:29.517 回答
7

另一种方式可能是。

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 调用中,放置驱动程序变量和等待秒数。

于 2016-01-19T23:01:42.850 回答