You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Firefox Headless、Selenium与Python时遇连接拒绝错误求助

解决EC2 Ubuntu上无头Firefox+Selenium的Connection Refused错误

我来帮你排查这个问题!这种Connection refused错误在EC2的无头环境里挺常见的,除了你已经检查过的版本兼容和重启实例,还有几个关键要点可以逐一排查:

1. 确认Firefox本体已正确安装且能运行

EC2的Ubuntu默认没有预装Firefox,无头模式也依赖Firefox客户端本身:

  • 先检查Firefox是否存在:执行which firefox,如果没有输出,就用下面的命令安装:
    sudo apt update && sudo apt install firefox -y
    
  • 测试Firefox无头启动是否正常:
    firefox --headless --url https://google.com --new-window
    
    如果这条命令报错,说明Firefox本身启动有问题,得先解决这个基础问题。

2. 检查geckodriver的权限与路径配置

  • 先确认geckodriver有可执行权限:
    ls -l /home/ubuntu/geckodriver
    
    输出里如果没有x权限,就执行sudo chmod +x /home/ubuntu/geckodriver添加可执行权限。
  • 建议把geckodriver放到系统全局路径(比如/usr/local/bin/),这样代码里可以省略executable_path参数,避免路径配置错误:
    sudo cp /home/ubuntu/geckodriver /usr/local/bin/
    

3. 适配Selenium版本的代码写法

如果你用的是Selenium 4.x版本,官方已经推荐使用Service类来管理驱动,而不是直接在webdriver.Firefox里传executable_path,调整后的代码如下:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

options = Options()
# 新版本Firefox推荐用这个参数开启无头模式
options.add_argument("--headless=new")
# 如果已经把geckodriver放到全局路径,这里可以不用写path
service = Service('/home/ubuntu/geckodriver')
driver = webdriver.Firefox(service=service, options=options)

try:
    driver.get("https://google.com")
    print('Done')
finally:
    driver.quit()

4. 查看geckodriver日志定位细节

启动驱动时开启日志输出,能帮你找到更具体的错误原因:

service = Service('/home/ubuntu/geckodriver', log_path='/tmp/geckodriver.log')

运行代码后查看日志:

cat /tmp/geckodriver.log

日志里会显示Firefox启动失败的具体原因(比如依赖缺失、配置错误等)。

5. 排查系统防火墙与网络

  • 检查Ubuntu的ufw防火墙状态:sudo ufw status,如果是开启状态,可以先临时关闭测试:sudo ufw disable,确认是否是防火墙拦截了本地连接。
  • 确认EC2实例能正常访问外部网络:curl https://google.com,如果无法访问,需要检查实例的安全组和路由表配置。

先从这些步骤开始排查,大部分情况下都是Firefox未安装、驱动权限不足或者代码写法不匹配导致的问题。

内容的提问来源于stack exchange,提问作者Mojo Jojo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:32:38