使用undetected_chromedriver与Selenium多进程运行问题求助
多进程结合undetected_chromedriver与Selenium的问题解决
问题描述
- 未设置
use_multi_procs=True时,多个浏览器能打开,但仅第一个实例可执行任务,其余停留在Chrome启动页 - 设置
use_multi_procs=True时,出现[WinError 5]权限拒绝错误,涉及路径C:\Users\clecl\appdata\roaming\undetected_chromedriver\undetected\chromedriver-win32,且该目录只读属性无法永久取消
解决方案
1. 绕过系统只读目录,指定自定义chromedriver路径
undetected_chromedriver默认会把驱动文件存到系统漫游目录,该目录权限受限。手动下载与Chrome版本匹配的chromedriver,放到脚本同级目录,初始化时通过driver_executable_path参数指定自定义路径,避开系统目录。
2. 正确配置多进程参数
必须在uc.Chrome()中同时设置use_multi_procs=True和自定义驱动路径,确保每个进程使用独立的驱动实例,避免资源竞争导致的启动异常。
3. 代码优化(可选)
避免使用exec执行方法,改用更安全的属性调用方式;添加进程join()方法,防止主进程提前退出导致子进程异常。
修改后的可运行代码
from selenium import webdriver import multiprocessing import undetected_chromedriver as uc import os class Bot: def __init__(self, profile: str, chrome_path: str, driver_path: str): options = uc.ChromeOptions() options.add_argument(f"--user-data-dir={chrome_path}") options.add_argument(f'--profile-directory={profile}') # 配置多进程参数+自定义驱动路径 self.driver = uc.Chrome( options=options, use_multi_procs=True, driver_executable_path=driver_path ) def open_chrome(self): self.driver.get("https://www.google.com") def open_youtube(self): self.driver.get("https://www.youtube.com") def open_amazon(self): self.driver.get("https://www.amazon.com") # 配置路径 chrome_path = r"C:\Users\clecl\OneDrive\Documents\Bot\User Data" # 替换为你下载的chromedriver.exe的路径,示例为脚本同级目录 driver_path = os.path.join(os.getcwd(), "chromedriver.exe") PROFILE = [ {"profile": "Default"}, {"profile": "Profile 1"} ] def run_bot(profile, chrome_path, driver_path): ACTION_CHAIN = [ "open_chrome", "open_youtube", "open_amazon" ] b = Bot(profile=profile, chrome_path=chrome_path, driver_path=driver_path) for action in ACTION_CHAIN: # 替换exec为更安全的调用方式 method = getattr(b, action, None) if method: method() # 执行完成后关闭驱动 b.driver.quit() if __name__ == "__main__": processes = [] for p in PROFILE: process = multiprocessing.Process( target=run_bot, args=(p["profile"], chrome_path, driver_path) ) processes.append(process) process.start() # 等待所有子进程完成 for process in processes: process.join()
额外说明
- 下载chromedriver时,需确保版本与你的Chrome浏览器版本完全匹配
- 复制的Chrome用户数据目录需确保没有被其他Chrome进程占用,否则会导致启动失败
内容的提问来源于stack exchange,提问作者Berthouille
相关产品推荐
相关产品推荐

