Selenium多线程优化:自动Checkout Bot批量实例高效实现问询
解决方案
1. 优化重复代码的实现
你的代码中重复创建Main1/2/3函数以及手动逐个实例化Chrome驱动的写法,完全可以通过循环+通用函数来简化:
步骤1:合并重复的Main函数
将多个索引专属的Main函数替换为一个接受索引参数的通用函数:
def run_bot(i): login(i) checkout(i)
步骤2:用循环创建线程
不再手动创建p1/p2/p3,而是遍历驱动列表的索引批量生成线程:
import threading # 先整理好所有实例的options到列表中 options_list = [options1, options2, options3] # 用列表推导式批量生成驱动实例,替代手动重复书写 driver = [uc.Chrome(use_subprocess=True, options=opt) for opt in options_list] # 批量创建并启动线程 threads = [] for i in range(len(driver)): thread = threading.Thread(target=run_bot, args=(i,)) threads.append(thread) thread.start() # 可选:等待所有线程执行完成(根据业务需求选择是否添加) for thread in threads: thread.join()
这样既消除了重复的函数定义,也简化了线程的创建逻辑,后续新增实例只需在options_list中添加配置即可。
2. 支持输入指定实例数量
要实现动态指定实例数,核心是根据输入数量动态生成账户配置和驱动实例,无需手动修改代码:
步骤1:获取用户输入的实例数量
instance_count = int(input("请输入要启动的Bot实例数量: "))
步骤2:动态生成账户配置与驱动
首先需要一个能根据索引生成对应账户配置(包括Chrome Options、登录信息等)的逻辑,你可以根据实际存储方式(配置文件、数据库等)调整:
def get_account_config(index): """根据索引返回对应账户的Chrome配置和登录信息""" # 示例:生成专属用户数据目录,避免多实例浏览器数据冲突 options = uc.ChromeOptions() options.add_argument(f"--user-data-dir=./bot_profiles/profile_{index}") # 可添加更多专属配置,比如代理、浏览器语言等 # 实际场景中可替换为从JSON/CSV读取真实账户信息 account_info = { "username": f"account_{index}", "password": f"password_{index}" } return options, account_info
步骤3:批量创建驱动与线程
driver = [] threads = [] account_details = [] for i in range(instance_count): # 获取当前实例的配置 options, info = get_account_config(i) account_details.append(info) # 创建驱动实例 driver_instance = uc.Chrome(use_subprocess=True, options=options) driver.append(driver_instance) # 创建并启动线程 thread = threading.Thread(target=run_bot, args=(i,)) threads.append(thread) thread.start() # 等待所有线程完成 for thread in threads: thread.join()
可选:调整run_bot函数适配动态账户信息
如果login和checkout需要直接使用账户信息,可以修改run_bot:
def run_bot(i): login(i, account_details[i]) checkout(i, account_details[i])
这样就实现了完全动态的实例数量控制,新增实例只需输入对应数字,无需手动修改函数或驱动列表。
内容的提问来源于stack exchange,提问作者Glitch
相关产品推荐
相关产品推荐

