Mac环境下undetected-chromedriver无法运行,报session创建失败错误
解决Mac上undetected-chromedriver无法连接Chrome的问题
针对你遇到的session not created: cannot connect to chrome错误,以下是几个针对性的排查和修复步骤:
1. 修正Chrome用户数据目录路径
Mac系统中Chrome的默认用户数据目录并非/Users/.../Google/Chrome,正确路径通常是:
~/Library/Application Support/Google/Chrome
若需指定具体用户配置文件(比如默认配置),路径为:
~/Library/Application Support/Google/Chrome/Default
注意将~替换为你的实际用户目录(如/Users/yourname),且必须完全关闭所有Chrome窗口及后台进程后再运行代码,避免路径被占用。
2. 强制清理Chrome残留进程
后台残留的Chrome进程可能占用端口,导致无法新建会话。打开终端执行以下命令彻底清理:
pkill -9 Chrome pkill -9 chromedriver
等待几秒后重新运行Python代码。
3. 手动指定Chrome二进制文件路径
若undetected-chromedriver无法自动识别Chrome安装位置,手动添加二进制路径参数:
options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
将这行代码加入options配置部分,若使用Chrome Beta等特殊版本,需对应调整路径。
4. 简化配置逐步排查
暂时移除可能冲突的参数,先尝试基础配置启动,确认核心功能正常后再逐个添加参数:
import undetected_chromedriver as uc options = uc.ChromeOptions() options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("--no-sandbox") # 手动指定二进制路径(推荐) options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" driver = uc.Chrome(options=options)
若基础配置可正常启动,再依次添加user-data-dir、user-agent等参数,定位冲突来源。
5. 检查目录权限
确保Python进程对指定的user-data-dir有读写权限,终端执行以下命令修改权限(替换为你的实际路径):
chmod -R 755 "/Users/yourname/Library/Application Support/Google/Chrome"
内容的提问来源于stack exchange,提问作者Rony Tesler
相关产品推荐
相关产品推荐

