服务器运行Flask+Thread程序时ChromeDriver的正确路径该如何设置
服务器场景ChromeDriver路径配置解决方法
- 首先排查操作系统匹配问题:本地Windows使用的
chromedriver.exe仅适用于Windows系统,如果你的服务器是Linux/macOS系统,需要下载对应服务器架构、对应Chrome版本的无后缀二进制ChromeDriver文件,放置到程序目录后还需要给驱动赋执行权限,执行命令:chmod +x chromedriver - 优先使用绝对路径替代相对路径:Flask应用启动时的工作目录不一定等于你的代码文件所在目录,使用相对路径会出现文件找不到的问题,可通过os模块构造绝对路径,示例代码如下:
import os # 获取当前脚本所在的绝对目录 current_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接chromedriver的绝对路径,Windows服务器保留.exe后缀,Linux/macOS去掉后缀 driver_path = os.path.join(current_dir, "chromedriver") driver = webdriver.Chrome(executable_path=driver_path, options=options)
- 可选简化配置:将ChromeDriver文件放到系统环境变量PATH包含的目录中,比如Linux系统的
/usr/local/bin目录,此时不需要在代码中指定executable_path参数,Selenium会自动检索匹配的驱动文件。
注意:无桌面的Linux服务器运行Chrome必须开启无头模式,且添加必要启动参数,否则会启动失败,参数配置示例:
options.add_argument("--headless=new") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage")同时服务器必须安装与ChromeDriver版本匹配的Chrome浏览器,仅放置驱动文件无法正常运行。
内容的提问来源于stack exchange,提问作者DisplayMoto
相关产品推荐
相关产品推荐

