Google Cloud Ubuntu VM运行Selenium报geckodriver需加入PATH
Selenium在GCP Ubuntu虚拟机触发geckodriver缺失报错的修复方案
核心问题定位
放置chromedriver却触发'geckodriver' executable needs to be in PATH报错,本质是Chrome驱动初始化流程未正常走通,Selenium自动驱动匹配逻辑错误触发Firefox驱动检测规则,无需安装geckodriver,按以下步骤修复即可:
步骤1:修正代码中的驱动初始化逻辑
不要使用无参数的默认驱动初始化方式,必须显式指定Chrome驱动路径、无头运行参数,避免Selenium匹配错误驱动,参考如下初始化代码:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service import os # 定位当前py文件同目录下的chromedriver driver_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chromedriver") chrome_opt = Options() # 云服务器无桌面环境必须添加的运行参数 chrome_opt.add_argument("--headless=new") chrome_opt.add_argument("--no-sandbox") chrome_opt.add_argument("--disable-dev-shm-usage") chrome_opt.add_argument("--disable-gpu") # 显式传入驱动服务和配置,禁止Selenium自动探测驱动 service = Service(executable_path=driver_path) driver = webdriver.Chrome(service=service, options=chrome_opt)
注意:全局搜索代码确认不存在webdriver.Firefox()的误写。
步骤2:修复服务器端文件与环境配置
- 给chromedriver添加可执行权限,上传到Linux系统的文件默认无执行权限,在test.py所在目录执行命令:
执行完可以运行chmod +x ./chromedriver./chromedriver --version验证,如果正常输出版本号说明驱动文件本身可用。 - 确认已在Ubuntu虚拟机安装Chrome浏览器,仅放置chromedriver无法运行,执行以下命令安装稳定版Chrome:
安装完成后执行wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo apt install ./google-chrome-stable_current_amd64.deb -ygoogle-chrome --version查看版本号,确保你放置的chromedriver大版本和Chrome版本完全一致,版本不匹配会直接导致Chrome启动失败。 - 安装Chrome无头运行依赖的系统库,避免因缺少依赖启动失败:
sudo apt update && sudo apt install -y libx11-xcb1 libxcomposite1 libxcursor1 libxdamage1 libxi6 libxtst6 libnss3 libcups2 libxss1 libxrandr2 libasound2 libpangocairo-1.0-0 libatk1.0-0 libatk-bridge2.0-0 libgtk-3-0
步骤3:验证运行
回到test.py所在目录,执行python test.py即可正常启动Chrome驱动完成数据抓取逻辑,Discord机器人可正常保持在线。
内容的提问来源于stack exchange,提问作者Klasyt
相关产品推荐
相关产品推荐

