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

如何解决Python中Try/Except误触发非Captcha错误的问题?

仅在Captcha错误时触发VPN重启的解决方案

要让restart_program只在检测到Virustotal验证码时执行,需要通过自定义异常和精准的Captcha检测逻辑区分验证码错误与其他普通错误,具体修改步骤如下:

1. 定义自定义异常类

专门创建异常类标记验证码检测事件,让代码逻辑更清晰:

class CaptchaDetectedError(Exception):
    """用于标记检测到Virustotal验证码的异常"""
    pass

2. 在扫描函数中检测Captcha并抛出异常

修改perform_Scan函数,加入Captcha检测逻辑,发现验证码就抛出自定义异常(注意传入driver对象,处理Shadow DOM元素):

def perform_Scan(IOC, driver):
    # 保留原有扫描逻辑(打开Virustotal页面、输入IOC等)
    
    # 检测是否出现Captcha
    try:
        # 通过JavaScript获取Shadow DOM内的captchaContainer元素
        captcha_element = driver.execute_script("""
            return document.querySelector('vt-ui-shell').shadowRoot.querySelector('captchaContainer');
        """)
        if captcha_element is not None:
            raise CaptchaDetectedError("Virustotal要求验证,需更换IP")
    except Exception:
        # 元素不存在或执行脚本出错,说明无验证码,继续执行
        pass
    
    # 保留原有后续扫描逻辑(等待结果、提取信息等)

3. 调整主函数的Try/Except逻辑

在主循环中针对每个IOC的扫描单独捕获异常,仅在捕获到CaptchaDetectedError时调用restart_program,其他错误仅记录日志并继续执行:

import os
import subprocess
import time
from selenium import webdriver

# 这里放入你定义的CaptchaDetectedError和restart_program函数

if __name__ == "__main__":
    program_path = r"C:\Program Files\Cloudflare\Cloudflare WARP\Cloudflare WARP.exe"

    while True:
        driver = None
        try:
            driver = webdriver.Chrome()

            # 读取上次重启的位置
            try:
                with open('restart_position.txt', 'r') as f:
                    restart_position = int(f.read())
            except FileNotFoundError:
                restart_position = 0

            with open('IOCs.txt', 'r') as file:
                IOCs = [line.strip() for line in file if line.strip()]

            scan_completed = True
            for i, IOC in enumerate(IOCs[restart_position:], start=restart_position):
                try:
                    perform_Scan(IOC, driver)
                    # 扫描成功,更新重启位置为下一个IOC的索引
                    with open('restart_position.txt', 'w') as f:
                        f.write(str(i + 1))
                except CaptchaDetectedError as e:
                    print(e)
                    # 仅当检测到验证码时重启VPN
                    restart_program(program_path, i, driver)
                    scan_completed = False
                    break  # 跳出循环,等待重启后重新执行
                except Exception as e:
                    # 处理其他错误(如网络超时、页面加载失败等),不重启VPN
                    print(f"扫描IOC [{IOC}] 时出错: {str(e)}")
                    continue

            if scan_completed:
                # 所有IOC扫描完成,重置重启位置并退出
                with open('restart_position.txt', 'w') as f:
                    f.write("0")
                print("所有IOC扫描完成,程序退出")
                driver.quit()
                break
        except Exception as e:
            print(f"主程序出错: {str(e)}")
            if driver:
                driver.quit()
            time.sleep(30)  # 出错后等待30秒再重试

关键修改说明

  • 精准错误区分:通过自定义异常彻底分离验证码错误与其他类型错误,避免误触发VPN重启。
  • 主动检测Captcha:利用JavaScript直接查询Shadow DOM内的验证码容器,比等待超时更高效准确。
  • 重启位置管理:每次成功扫描后更新位置,重启后从断点继续,避免重复劳动。

内容的提问来源于stack exchange,提问作者ahmed osama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:43:24