Python Selenium Webdriver - 尝试异常循环

18 投票
2 回答
64158 浏览
提问于 2025-04-18 00:32

我正在尝试自动化一个逐帧加载的网页上的操作。我想设置一个 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 之前使用 time.sleep(),而不是在 except 之后。

谢谢

2 个回答

8

还有一种方法可以这样做。

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

36

你问的具体问题的答案是:

from selenium.common.exceptions import NoSuchElementException

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

不过,有一种更好的方法可以等到页面上的元素出现,那就是使用等待功能

撰写回答