使用Selenium/Python/Linux从Chrome切换到Chromium时出现段错误
解决Chromium + Selenium无头模式下的libstdc++.so段错误问题
可能的解决方案
1. 升级libstdc++依赖库
Oracle Linux 8默认的libstdc++版本可能无法完全适配Chromium 111的运行需求,段错误大概率是库版本不兼容导致的:
- 执行命令升级libstdc++及其开发包:
sudo dnf update libstdc++ sudo dnf install libstdc++-devel - 检查升级后的库版本是否满足要求:
确保输出中包含strings /usr/lib64/libstdc++.so.6 | grep GLIBCXXGLIBCXX_3.4.26及以上版本。
2. 优化Chromium启动参数
调整现有参数,移除冗余项并添加稳定性相关参数:
options = Options() options.add_argument("headless=new") # 使用Selenium 4支持的新无头模式,稳定性优于旧版 options.add_argument("--incognito") options.add_argument("--disable-gpu") options.add_argument("--no-sandbox") options.add_argument("--enable-javascript") options.add_argument("--disable-dev-shm-usage") # 解决Linux环境共享内存不足问题 options.add_argument("--single-process") # 单进程模式减少多进程崩溃概率 options.add_argument("--disable-extensions") # 禁用扩展避免冲突 options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) options.add_argument('--disable-blink-features=AutomationControlled') options.add_argument("--window-size=1920,1080") options.binary_location = '/usr/bin/chromium-browser'
注意:移除了重复的
--nogpu参数,替换旧版headless为headless=new。
3. 替换不稳定的JS/CDP调用方式
原代码中直接执行execute_script和setUserAgentOverride可能触发崩溃,改用更稳定的实现:
- 用CDP的
Page.addScriptToEvaluateOnNewDocument注入webdriver隐藏脚本:# 替换原browser.execute_script(...) browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) - 直接通过启动参数设置UserAgent,避免CDP调用:
# 替换原browser.execute_cdp_cmd(...) options.add_argument(f'--user-agent={userAgent}')
4. 验证Chromium与ChromeDriver的兼容性
虽然版本号一致,但需确认安装包来源:
- 确保Chromium和ChromeDriver均为官方对应版本,避免第三方编译包的兼容性问题;
- 可重新下载Chromium 111.0.5563.146和对应ChromeDriver替换现有文件。
5. 最小化用例排查
先运行最小测试脚本确认基础环境正常:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service options = Options() options.add_argument("headless=new") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.binary_location = '/usr/bin/chromium-browser' ser = Service("/usr/bin/chromedriver") browser = webdriver.Chrome(service=ser, options=options) browser.get("https://www.google.com") print(browser.title) browser.quit()
若此脚本无错误,再逐步添加原代码中的参数和操作,定位触发崩溃的具体步骤。
内容的提问来源于stack exchange,提问作者NazariGamer
相关产品推荐
相关产品推荐

