Python Selenium脚本启动Chrome运行异常问题求助
Selenium脚本启动Chrome后挂起、不加载目标页问题解决方案
故障表现
- 脚本运行后仅打开Chrome默认新标签页,不会跳转至目标地址
https://pcgarage.ro/ - 打印页面标题、
driver.quit()等后续逻辑完全不触发,进程持续挂起,只能通过终端按CTRL+C强制终止 - 相同逻辑使用Firefox驱动可正常执行,因项目要求需处理marionette相关问题故切换至Chrome方案
故障原因
代码中直接将Chrome浏览器本体路径/usr/bin/google-chrome作为参数传入webdriver.Chrome(),该参数在Selenium 4版本中用于接收ChromeDriver服务路径而非浏览器路径,参数传错会导致驱动与浏览器的通信握手失败,进程阻塞在建连阶段,无法执行后续指令。
修复方法
- 安装与本机Chrome大版本完全匹配的ChromeDriver,Debian/Ubuntu系Linux可直接通过包管理器安装:
sudo apt update && sudo apt install chromium-chromedriver -y - 替换原有错误的初始化代码,显式分离浏览器配置与驱动服务配置:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options # 初始化Chrome配置项 chrome_opts = Options() # 单独指定Chrome浏览器本体的二进制路径 chrome_opts.binary_location = "/usr/bin/google-chrome" # 若运行环境无图形界面,可放开下面的无头模式参数 # chrome_opts.add_argument("--headless=new") # 单独指定ChromeDriver路径,apt安装的默认路径为/usr/bin/chromedriver,手动安装的替换为实际路径即可 chrome_service = Service(executable_path="/usr/bin/chromedriver") # 按正确参数初始化驱动实例 driver = webdriver.Chrome(service=chrome_service, options=chrome_opts) # 原有业务逻辑无需改动 driver.get("https://pcgarage.ro/") print(driver.title) driver.quit() - 运行脚本前先清理残留进程,避免端口被占用导致连接失败:
pkill -9 google-chrome pkill -9 chromedriver
附:Firefox Marionette问题通用处理方案
如果后续需要切回Firefox满足项目要求,Marionette相关报错基本为配置缺失导致,按以下方式初始化即可覆盖绝大多数场景:
from selenium import webdriver from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options firefox_opts = Options() # 显式开启Marionette协议 firefox_opts.marionette = True # 替换为你本机geckodriver的实际路径 firefox_service = Service(executable_path="/usr/bin/geckodriver") driver = webdriver.Firefox(service=firefox_service, options=firefox_opts)
处理时注意三个要点:
- 保证geckodriver大版本与本机安装的Firefox大版本匹配,不要使用3年以上的旧版本geckodriver
- 非必要不要用root权限运行Selenium脚本,如果必须用root运行,需要额外添加
--no-sandbox启动参数 - 每次运行前清理残留的firefox、geckodriver进程,避免遗留进程占用调试端口
内容的提问来源于stack exchange,提问作者Ioana David
相关产品推荐
相关产品推荐

