在远程Windows服务器运行Chrome WebDriver遇chrome not reachable错误求助
解决Selenium ChromeDriver报"chrome not reachable"问题(PyInstaller打包远程Windows运行场景)
问题背景
本地编写Python Selenium脚本,用PyInstaller打包为exe后放到未安装Python的远程Windows服务器运行,Chrome与ChromeDriver版本匹配、文件结构正确、权限充足,但触发错误:
selenium.common.exceptions.WebDriverException: Message: chrome not reachable
相关代码片段:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import os options = Options() options.add_argument("download.default_directory={}".format(os.getcwd())) options.add_argument("--headless") options.add_argument("--disable-gpu") options.add_argument("--no-sandbox") options.add_argument("--disable-setuid-sandbox") options.add_argument("--remote-debugging-port=9222") options.binary_location = ".\\chrome-win32\\chrome.exe" service = Service(executable_path=".\\chrome-win32\\driver\\chromedriver.exe") driver = webdriver.Chrome(service=service, options=options)
针对性解决方案
1. 修正路径问题:使用exe所在的绝对路径
PyInstaller打包后的exe运行时,os.getcwd()可能指向用户当前工作目录而非exe所在目录,导致Chrome和Driver的相对路径失效。替换为获取exe的绝对路径:
import sys import os # 获取exe所在的目录 def get_exe_dir(): if hasattr(sys, '_MEIPASS'): # 打包后临时目录(--onefile模式) return sys._MEIPASS else: # 开发环境或--onedir模式下的目录 return os.path.dirname(os.path.abspath(__file__)) exe_dir = get_exe_dir() options = Options() # 下载目录改为exe所在目录 options.add_argument(f"download.default_directory={exe_dir}") # Chrome二进制文件绝对路径 options.binary_location = os.path.join(exe_dir, "chrome-win32", "chrome.exe") # ChromeDriver绝对路径 service = Service(executable_path=os.path.join(exe_dir, "chrome-win32", "driver", "chromedriver.exe"))
2. 调整Headless模式参数
旧版--headless参数在部分Windows环境下存在兼容性问题,改用新的无头模式参数,并补充窗口尺寸设置:
# 替换原--headless和--disable-gpu参数 options.add_argument("--headless=new") options.add_argument("--window-size=1920,1080") # 移除Linux专用参数:--no-sandbox和--disable-setuid-sandbox在Windows下无效 options.add_argument("--disable-features=VizDisplayCompositor") # 解决部分无头渲染异常
3. 移除冲突的远程调试端口参数
--remote-debugging-port=9222可能导致端口占用或权限限制,先移除该参数测试:
# 删除此行 # options.add_argument("--remote-debugging-port=9222")
4. 检查Chrome运行依赖
远程Windows服务器可能缺少Chrome运行所需的32位VC++ Redistributable运行库,安装对应版本的运行库后重试。
5. 验证Chrome能否独立启动
直接在远程服务器上运行chrome-win32\chrome.exe,如果无法启动,说明Chrome本身存在文件损坏或依赖缺失问题,重新下载Chrome for Testing替换。
内容的提问来源于stack exchange,提问作者Nicholas Curtis
相关产品推荐
相关产品推荐

