远程服务器运行Selenium Firefox爬虫报进程意外关闭信号错误如何解决
Selenium初始化Firefox远程部署报错解决方案
问题说明
基于Python+Selenium开发的Twitter网页爬虫本地运行无异常,部署到Ubuntu 18.04远程服务器后,初始化Firefox驱动阶段触发报错,运行环境版本:
- Ubuntu 18.04.5
- selenium 3.141.0
- Mozilla Firefox 86.0
- geckodriver 0.29.0
报错堆栈信息:
File "twitter.py", line 435, in <module> twitter_walk() File "twitter.py", line 31, in twitter_walk driver = webdriver.Firefox(executable_path="./geckodriver",options=options) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__ keep_alive=True) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status signal
解决步骤
按以下优先级逐一排查,90%以上的同类问题都能在前两步解决:
- 开启无头模式+基础启动参数
远程服务器默认不带图形桌面环境,Firefox尝试启动可视化窗口会直接崩溃。初始化驱动时必须给Options添加无头相关参数,代码参考:from selenium.webdriver import FirefoxOptions options = FirefoxOptions() options.add_argument("--headless") # 启用无头模式,无图形界面下运行 options.add_argument("--disable-gpu") # 禁用GPU加速,服务器无独立显卡时规避渲染异常 options.add_argument("--no-sandbox") # 关闭沙箱,避免非root用户运行时的权限限制 driver = webdriver.Firefox(executable_path="./geckodriver", options=options) - 补全系统缺失的运行依赖
Ubuntu Server版本默认裁剪了大量桌面端依赖库,即便开启无头模式,Firefox也会因为缺库启动失败。执行以下命令安装全量依赖:
安装完成后执行apt update apt install -y firefox libgtk-3-0 libasound2 libx11-xcb1 libxcomposite1 libxcursor1 libxdamage1 libxi6 libxtst6 libnss3 libcups2 libxss1 libxrandr2 libgconf-2-4 libpangocairo-1.0-0 libatk1.0-0 libatk-bridge2.0-0firefox --headless --version验证,能正常输出版本号即代表依赖齐全。 - 修复文件执行权限
从本地上传到远程服务器的geckodriver、Firefox二进制文件可能丢失执行权限,执行命令重新赋权:
不要直接用root用户运行爬虫脚本,新建普通用户执行,规避不必要的权限限制。chmod +x ./geckodriver chmod +x /usr/bin/firefox - 解决路径冲突问题
你当前使用的Firefox86、geckodriver0.29、selenium3.141版本组合本身是兼容的,不需要更换版本。如果前面步骤操作完仍报错,检查服务器内是否存在多版本Firefox/geckodriver导致路径冲突,初始化时显式指定Firefox二进制路径即可:options.binary_location = "/usr/bin/firefox"
验证方式
配置修改完成后,不要直接运行全量爬虫,先写最简测试脚本:初始化driver后访问任意公开页面,打印页面标题,能正常返回即代表环境配置正确,再运行爬虫业务逻辑即可。
内容的提问来源于stack exchange,提问作者wixyty
相关产品推荐
相关产品推荐

