You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中遇异常时如何重新执行当前循环迭代?

解决WhatsApp批量发消息时当前号码重试的迭代问题

批量处理WhatsApp联系人发送消息时,若WebDriverWait超时导致当前号码无法发送,用continue会直接跳过该号码,手动修改for循环的迭代变量i也无法控制迭代流程——这是因为Python的for循环基于迭代器实现,每次迭代都会自动取下一个元素,修改i变量不会影响迭代器的位置。

可行解决方案:用索引控制的while循环替代for循环

通过索引追踪当前处理的号码,仅当消息发送成功时才递增索引,失败则保持索引不变,重新处理当前号码:

from selenium.common.exceptions import TimeoutException

index = 0
total_numbers = len(numbers)

while index < total_numbers:
    current_number = numbers[index]
    try:
        # 等待发送框可点击
        WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, self.send_message_box_element)))
        # 发送消息(确保send_message能接收当前号码参数)
        send_message(current_number)
        # 成功发送后,处理下一个号码
        index += 1
    except TimeoutException:
        # 执行重试前置操作(比如返回联系人列表重新定位)
        go_back_and_try_again_send_message_to_number_aux()
        # 不递增索引,下次循环继续处理当前号码

另一种思路:嵌套重试循环

如果不想改变外层循环结构,可在for循环内嵌套while循环,专门处理当前号码的重试逻辑,直到发送成功:

from selenium.common.exceptions import TimeoutException

for current_number in numbers:
    send_success = False
    while not send_success:
        try:
            WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, self.send_message_box_element)))
            send_message(current_number)
            send_success = True
        except TimeoutException:
            go_back_and_try_again_send_message_to_number_aux()
            # 继续循环重试当前号码

注意事项

  • 避免使用裸except,应捕获具体的TimeoutException,防止捕获无关异常(如元素定位失败、网络错误)导致逻辑混乱。
  • 可根据实际需求给重试添加次数限制,避免无限循环(例如重试3次后跳过该号码)。

内容的提问来源于stack exchange,提问作者Davi Americo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:17:23