基于Python+Selenium的Sneaker-Bot如何实现账号读取与自定义线程数配置
账号凭证存储与读取实现
优先选择用户编辑门槛低、程序解析稳定的格式,两种常用实现方式可直接落地:
JSON格式实现
结构化程度高、不易出现格式歧义,是推荐首选方案
- 约定文件结构:程序同级目录下的
accounts.json存储所有账号,结构固定为账号列表
{ "accounts": [ {"username": "buyer01", "password": "pass123"}, {"username": "buyer02", "password": "pass456"} ] }
- 读取逻辑直接用Python内置
json模块实现,首次运行自动生成空模板降低用户使用成本,代码片段:
import json from pathlib import Path def load_accounts_json(file_path: str = "accounts.json") -> list[dict]: config_path = Path(file_path) if not config_path.exists(): # 无配置文件时自动生成模板 with open(config_path, "w", encoding="utf-8") as f: json.dump({"accounts": []}, f, indent=2, ensure_ascii=False) raise FileNotFoundError(f"请在{config_path.resolve()}中填写账号凭证后重启程序") with open(config_path, "r", encoding="utf-8") as f: config = json.load(f) return config.get("accounts", [])
基础安全提示:如果担心明文存储密码的风险,可以用简单的字符混淆逻辑替代原始明文,不需要引入复杂加密库,平衡易用性和基础防护能力。
纯文本格式实现
对普通用户更友好,不需要适配JSON语法规则
- 约定文件规则:程序同级目录下的
accounts.txt,每行存储1个账号,用固定分隔符----拆分用户名和密码,支持#开头的注释行、空行自动跳过 - 文件示例:
# 注释行,程序读取时自动跳过 buyer01----pass123 buyer02----pass456 buyer03----pass789
- 对应读取逻辑:
from pathlib import Path def load_accounts_txt(file_path: str = "accounts.txt") -> list[dict]: config_path = Path(file_path) if not config_path.exists(): # 首次运行自动生成带示例的模板 with open(config_path, "w", encoding="utf-8") as f: f.write("# 格式规则:每行1个账号,用----拆分用户名和密码\n示例用户----示例密码\n") raise FileNotFoundError(f"请在{config_path.resolve()}中按规则填写账号后重启程序") accounts = [] with open(config_path, "r", encoding="utf-8") as f: for line_num, line in enumerate(f.readlines(), 1): line = line.strip() # 跳过空行、注释行 if not line or line.startswith("#"): continue parts = line.split("----") if len(parts) != 2: raise ValueError(f"第{line_num}行格式错误,请检查是否按「用户名----密码」规则填写") accounts.append({ "username": parts[0].strip(), "password": parts[1].strip() }) return accounts
自定义线程数与账号绑定实现
核心逻辑要从机制上避免账号跨线程复用触发平台风控,实现步骤固定:
- 程序启动阶段先加载全部有效账号,统计总可用账号数N
- 引导用户输入要运行的线程数T,做强制校验:
- T必须为正整数
- T不能大于N,否则提示“当前仅配置N个可用账号,每个任务需绑定专属账号,最多支持启动N个任务”
- 按顺序为每个启动的线程绑定专属账号,即第i个线程绑定账号列表中索引为i的凭证,从逻辑上杜绝账号复用问题
- 每个线程独立初始化专属的Selenium WebDriver实例,严禁跨线程共享WebDriver对象,避免出现会话串号、元素定位错乱的问题
参考实现代码片段:
import threading # 替换成你已经开发完成的Sneaker Bot核心下单逻辑 def bot_core_logic(thread_id: int, account: dict): # 单独初始化当前线程的WebDriver # 调用已有核心逻辑完成登录、商品加购、下单流程 print(f"任务{thread_id}已启动,绑定账号:{account['username']}") def run_bootstrap(): # 二选一加载账号配置即可 all_accounts = load_accounts_json() # all_accounts = load_accounts_txt() if not all_accounts: raise RuntimeError("未检测到有效账号,请先完成配置") max_task_count = len(all_accounts) # 获取用户输入的任务数 while True: try: user_input = int(input(f"检测到{max_task_count}个可用账号,请输入要启动的任务数(最大支持{max_task_count}):")) if 1 <= user_input <= max_task_count: run_task_count = user_input break print(f"输入超出范围,请输入1到{max_task_count}之间的整数") except ValueError: print("输入格式错误,请输入合法整数") # 启动对应任务,一一绑定账号 thread_list = [] for idx in range(run_task_count): # 索引对应绑定专属账号,无复用 bound_account = all_accounts[idx] task_thread = threading.Thread(target=bot_core_logic, args=(idx, bound_account)) thread_list.append(task_thread) task_thread.start() # 等待所有任务执行完成 for t in thread_list: t.join() if __name__ == "__main__": run_bootstrap()
可扩展优化点:如果需要更灵活的账号选择逻辑,可以在启动阶段把所有账号列表打印出来,让用户手动勾选要参与运行的账号,再根据选中的账号数启动对应数量的线程,无需绑定全部账号。
内容的提问来源于stack exchange,提问作者programming_for_fun
相关产品推荐
相关产品推荐

