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

Selenium报错求助:'Options'无set_headless属性及geckodriver异常

解决Selenium爬虫的两个常见错误

1. 修复AttributeError: 'Options' object has no attribute 'set_headless'

Selenium 4.0及以上版本已彻底废弃set_headless()方法,针对Firefox的无头模式设置,推荐使用命令行参数的方式,比直接设置headless = True兼容性更好:

from selenium.webdriver.firefox.options import Options

opts = Options()
# Selenium 4.8+ 推荐使用 "--headless=new"(更稳定的无头模式)
opts.add_argument("--headless=new")
# 若使用Selenium 4.7.x,也可使用旧版参数 "--headless"
# opts.add_argument("--headless")

2. 解决WebDriverException: geckodriver服务意外退出,状态码-6

状态码-6的核心原因多为版本不兼容、权限不足或Firefox路径问题,按以下顺序排查:

  • 版本匹配检查:
    确保Firefox、geckodriver、Selenium三者版本对应:
    • Selenium 4.7.2需搭配geckodriver 0.32+,Firefox版本建议102及以上;
    • 可通过firefox --version和geckodriver --version查看当前版本,若不匹配,下载对应版本的geckodriver即可。
  • 权限与可执行性:
    Linux/macOS用户需确保geckodriver有可执行权限,执行命令:
    chmod +x /path/to/geckodriver
    
  • 显式指定Firefox二进制路径:
    部分系统会出现找不到Firefox的情况,手动指定路径:
    # 根据你的系统替换路径
    opts.binary_location = "/usr/bin/firefox"  # Linux
    # opts.binary_location = "C:\\Program Files\\Mozilla Firefox\\firefox.exe"  # Windows
    # opts.binary_location = "/Applications/Firefox.app/Contents/MacOS/firefox"  # macOS
    
  • 禁用沙箱(临时测试):
    部分环境下Firefox沙箱会导致进程崩溃,添加参数禁用:
    opts.add_argument("--no-sandbox")
    opts.add_argument("--disable-dev-shm-usage")
    

完整可运行示例

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

def init_driver():
    opts = Options()
    opts.add_argument("--headless=new")
    opts.binary_location = "/usr/bin/firefox"  # 替换为你的Firefox实际路径
    opts.add_argument("--no-sandbox")
    opts.add_argument("--disable-dev-shm-usage")
    
    driver = webdriver.Firefox(options=opts)
    return driver

if __name__ == "__main__":
    driver = init_driver()
    driver.get("https://example.com")
    print(driver.title)
    driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:55:38