Python多进程配合Selenium 按行分配userpass.txt实现并发登录
多进程独立分配账号登录的实现代码
原代码核心问题
- 任务函数
do_something没有接收账号参数,所有进程启动后不会读取账号列表内容 - 手动创建固定3个进程的方式,无法自动遍历文件内所有账号条目,也没有任务分配机制,容易出现多个进程使用同一条账号的问题
- Selenium驱动是进程隔离资源,跨进程共享会直接报错,必须每个子进程独立初始化自己的Chrome实例
可直接运行的修正版代码
import time import multiprocessing from selenium import webdriver def init_chrome_driver(): """每个子进程独立初始化Chrome驱动,避免跨进程资源冲突""" chrome_options = webdriver.ChromeOptions() # 在这里补充你原有的Chrome启动配置(比如无头模式、窗口大小等) # 如果使用旧版Selenium,把下方的options参数换回chrome_options即可 driver = webdriver.Chrome( options=chrome_options, executable_path="C:/Users/你的实际路径/chromedriver.exe" ) return driver def login_task(account_info): """接收单条账号作为入参,执行对应登录逻辑""" username1, password1 = account_info driver = init_chrome_driver() try: driver.get('http://你的目标登录地址') # 定位登录元素 username_input = driver.find_element_by_xpath('//*[@id="login-username"]') username_input.send_keys(username1) pwd_input = driver.find_element_by_xpath('//*[@id="login-password"]') pwd_input.send_keys(password1) login_btn = driver.find_element_by_id('login-button') login_btn.click() # 补充登录后需要的验证、操作逻辑 time.sleep(2) print(f"账号 {username1} 登录流程执行完成") finally: # 任务执行完必须主动关闭浏览器,避免后台残留进程 driver.quit() if __name__ == '__main__': # 读取账号文件 username_password_list = [] with open("userpass.txt", encoding="utf-8") as file: for line in file: line = line.strip() if not line: # 自动跳过文件里的空行 continue # 按第一个冒号拆分,避免密码中包含冒号导致拆分错误 username1, password1 = line.split(':', 1) username_password_list.append((username1.strip(), password1.strip())) # 创建进程池,设置并发进程数为3(和你原来计划的进程数一致) # 进程池会自动把每个账号作为独立任务,分发给空闲进程执行:哪个进程先跑完手里的任务,就自动领取列表里剩下的下一条账号,直到所有行都处理完成 with multiprocessing.Pool(processes=3) as pool: pool.map(login_task, username_password_list)
关键逻辑说明
- 账号分配规则:完全匹配你需要的效果——前3个账号会分别分给3个初始进程,后续每有一个进程跑完当前任务,就自动领取剩余账号列表的下一条,全程不会出现多个进程重复使用同一条账号的情况,也不需要手动循环分配。
- 新手容易踩的坑:
- 不要把driver实例存在全局变量里,多进程是内存隔离的,全局变量在子进程中是独立的副本,跨进程使用会触发Selenium报错
- 读取文件时一定要加
strip()处理换行符、首尾空格,避免因为行末的不可见字符导致账号密码输入错误 - 拆分账号密码时用
split(':', 1),即使密码里包含冒号也不会拆分错误 - 不需要手动调用
process.join()等待进程执行,进程池会自动等待所有任务跑完再退出程序
内容的提问来源于stack exchange,提问作者juniperberry
相关产品推荐
相关产品推荐

