PythonAnywhere部署undetected-chromedriver无法连接127.0.0.1Chrome报错如何解决
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1
问题诱因
- 代码配置参数未生效:预先定义的
chrome_options和chrome_path变量未传入uc.Chrome构造函数,本地环境存在默认路径匹配逻辑可正常运行,但PythonAnywhere沙箱环境路径规则严格,无法自动识别配置与驱动路径。 - 平台端口限制:PythonAnywhere环境默认拦截Chrome固定本地调试端口的连接请求,undetected-chromedriver默认启动的本地调试服务无法被正常访问。
- 版本适配问题:使用的旧版v2接口没有自动适配环境Chrome版本的逻辑,PythonAnywhere安装的Chrome版本与本地版本不一致会触发连接失败。
- 非法操作调用:无头模式下调用
maximize_window()窗口最大化操作会触发Chrome运行异常,中断连接。
解决方案
按以下规则修正代码即可:
- 构造
uc.Chrome实例时必须传入已配置的参数和chromedriver路径 - 新增
--remote-debugging-port=0参数,让Chrome随机选取可用端口,避开平台拦截规则 - 新增
--disable-dev-shm-usage参数,解决沙箱环境共享内存不足导致的Chrome启动失败问题 - 移除无头模式下无效的
maximize_window()调用 - 弃用已停止维护的v2版本导入方式,使用主包导入逻辑
修正后可运行代码示例:
import undetected_chromedriver as uc from shutil import which chrome_options = uc.ChromeOptions() # 使用新版无头模式参数,兼容性更好 chrome_options.add_argument("--headless=new") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") # 随机分配调试端口 chrome_options.add_argument("--remote-debugging-port=0") chrome_options.add_argument(f"user-agent={user_agents}") chrome_path = which("./chromedriver") drive = uc.Chrome( options=chrome_options, driver_executable_path=chrome_path, # 自动匹配当前环境Chrome主版本 version_main=None ) with drive: drive.get(Url) drive.implicitly_wait(5)
额外注意事项
- 先在PythonAnywhere控制台执行
google-chrome --version确认Chrome已正常安装,免费套餐默认未开放浏览器运行权限,需升级套餐或联系平台管理员开通。 - 若仍报错可手动指定PythonAnywhere环境安装的Chrome主版本号,将
version_main参数替换为对应数字即可。
内容的提问来源于stack exchange,提问作者Muhammad Aadil
相关产品推荐
相关产品推荐

