Selenium脚本无用户输入超时后自动选择默认配置文件执行方案咨询
实现方案
方案1:Python标准库实现(无第三方依赖)
利用threading模块实现超时监听,不需要额外安装任何包,兼容性最好,适配定时任务场景使用,完全区分「用户无操作超时」和「用户主动输入空内容/错误内容」的场景,afk超时场景符合需求:
import threading import time from selenium import webdriver # 你的凭证配置 credentials = { 'Default': ['default_user', 'default_password'], 'Adam': ['adam_user', 'adam_password'], 'Linus': ['linus_user', 'linus_password'] } # 按顺序生成选项列表,Default固定在第一位 profile_list = list(credentials.keys()) selected_profile = None input_event = threading.Event() def get_user_input(): global selected_profile try: selected_profile = input("请输入选择的配置文件序号:") except: pass input_event.set() # 打印选择提示 print("Choose your profile:") for idx, name in enumerate(profile_list, 1): print(f"{idx}. {name}") # 启动输入监听线程 input_thread = threading.Thread(target=get_user_input, daemon=True) input_thread.start() # 等待5秒输入 input_event.wait(timeout=5) # 处理选择结果 if selected_profile is None: print("\n超时未收到输入,自动使用Default配置") use_profile = "Default" else: try: select_idx = int(selected_profile) - 1 if 0 <= select_idx < len(profile_list): use_profile = profile_list[select_idx] else: print("输入序号无效,自动使用Default配置") use_profile = "Default" except ValueError: print("输入格式错误,自动使用Default配置") use_profile = "Default" # 拿到对应凭证 username, password = credentials[use_profile] print(f"当前使用配置:{use_profile},用户名:{username}") # 后面接你的Selenium登录逻辑即可
方案2:第三方库实现(代码更简洁)
适合本地调试使用,代码更精简:
- 先安装依赖:
pip install inputimeout - 实现代码:
from inputimeout import inputimeout, TimeoutOccurred from selenium import webdriver credentials = { 'Default': ['default_user', 'default_password'], 'Adam': ['adam_user', 'adam_password'], 'Linus': ['linus_user', 'linus_password'] } profile_list = list(credentials.keys()) print("Choose your profile:") for idx, name in enumerate(profile_list, 1): print(f"{idx}. {name}") try: selected_profile = inputimeout(prompt="请输入选择的配置文件序号:", timeout=5) try: select_idx = int(selected_profile) - 1 if 0 <= select_idx < len(profile_list): use_profile = profile_list[select_idx] else: print("输入序号无效,自动使用Default配置") use_profile = "Default" except ValueError: print("输入格式错误,自动使用Default配置") use_profile = "Default" except TimeoutOccurred: print("\n超时未收到输入,自动使用Default配置") use_profile = "Default" username, password = credentials[use_profile]
补充说明
- 定时任务运行时脚本会自动走默认配置,不需要人工干预,完全符合定时运行需求
- 如果需要调整超时等待时长,直接修改代码中
timeout参数的数值即可,单位为秒
内容的提问来源于stack exchange,提问作者anantdark
相关产品推荐
相关产品推荐

