写 Selenium 自动化脚本最头疼的是偶尔会遇到元素找不到、点击失败、网络波动等问题,导致脚本崩溃。最常用的“救命”方法就是自动重试机制,遇到异常自动再试几次,稳定性大大提升。
这篇给你讲讲我常用的自动重试思路和代码示例。
一、自动重试的核心思路
- 把可能失败的操作包一层 try/except
- 捕获异常后等待一段时间,再重试
- 限制最大重试次数,避免无限循环
- 重试成功就继续,失败就抛错或记录日志
二、简单示例:封装点击操作自动重试
import time
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException
def retry_click(driver, by, value, max_retry=3, wait_sec=2):
"""
自动重试点击元素
"""
for attempt in range(max_retry):
try:
elem = driver.find_element(by, value)
elem.click()
print(f"点击成功,尝试次数:{attempt + 1}")
return
except (NoSuchElementException, ElementClickInterceptedException) as e:
print(f"点击失败,准备重试:{attempt + 1},异常:{e}")
time.sleep(wait_sec)
raise Exception(f"多次点击失败,元素定位:{by}={value}")
三、用装饰器封装重试逻辑
如果你有很多操作想加重试,可以写个通用装饰器:
import functools
def retry(max_retry=3, wait_sec=2, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_retry):
try:
return func(*args, **kwargs)
except exceptions as e:
print(f"第{attempt + 1}次重试,异常:{e}")
time.sleep(wait_sec)
raise Exception(f"重试失败超过{max_retry}次")
return wrapper
return decorator
用法示例:
@retry(max_retry=5, wait_sec=1, exceptions=(NoSuchElementException,))
def click_button(driver):
btn = driver.find_element(By.ID, "submit")
btn.click()
四、结合显式等待更稳
重试配合 WebDriverWait
效果更好:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
@retry(max_retry=3, wait_sec=2, exceptions=(Exception,))
def wait_and_click(driver, by, value, timeout=10):
elem = WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((by, value)))
elem.click()
五、小结
- 自动重试能大幅提升 Selenium 脚本稳定性
- 不要盲目无限重试,合理限制次数和等待时间
- 尽量结合显式等待,重试目标是“操作失败”而非“元素没出现”
- 养成给关键操作写重试的习惯,尤其是点击、输入、跳转