You need to enable JavaScript to run this app. Python环境下Selenium WebDriver处理不受信任网站证书的方法
优惠活动
大模型
产品
解决方案
定价
更多

Python环境下Selenium WebDriver处理不受信任网站证书的方法

Selenium启动Firefox 85.0.1跳过不受信任证书告警的实现方案

原有测试方案的失效原因

你之前尝试的两组配置没有生效,核心是两个适配偏差:

  • acceptSslCerts是面向Chrome、旧版IE浏览器的兼容能力字段,Firefox 70版本之后就不再识别该配置;就算启用注释里的acceptInsecureCerts,仅通过DesiredCapabilities传递配置也会因为缺少浏览器端的偏好同步,无法触达证书弹窗的拦截逻辑。
  • 旧版FirefoxProfile类的accept_untrusted_certs属性在Firefox 85版本已经被废弃,不再和实际的证书校验流程绑定,仅设置这个属性不会改变浏览器的安全弹窗触发规则。

可直接生效的标准配置

方案1:使用FirefoxOptions集成配置(推荐)

通过Selenium原生的Options类同时传递驱动能力配置和浏览器端偏好,不需要依赖临时Profile,即可完全跳过证书告警:

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

# 初始化Firefox配置实例
firefox_options = Options()
# 标记驱动层接受所有不受信任的TLS证书
firefox_options.set_capability("acceptInsecureCerts", True)
# 同步配置浏览器端证书校验规则,关闭告警弹窗触发逻辑
firefox_options.set_preference("security.enterprise_roots.enabled", True)
firefox_options.set_preference("security.cert_pinning.enforcement_level", 0)
firefox_options.set_preference("browser.xul.error_pages.expert_bad_cert", True)

# 启动浏览器访问目标站点
driver = webdriver.Firefox(options=firefox_options)
driver.get("目标站点地址")

方案2:自定义持久化Profile配置修正

如果使用独立的Firefox配置文件实现持久化配置,需要补充缺失的关键配置项,避免Selenium启动时覆盖自定义规则:

  • 打开对应配置文件目录下的prefs.js文件,补入三个核心配置:
    • user_pref("acceptInsecureCerts", true);
    • user_pref("security.cert_pinning.enforcement_level", 0);
    • user_pref("browser.xul.error_pages.expert_bad_cert", true);
  • 启动驱动时通过Options指定该Profile路径,注意不要同时传入旧版的firefox_profile参数,多参数传递时Selenium会优先使用临时生成的Profile覆盖自定义配置:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

firefox_options = Options()
# 指定独立配置文件的绝对路径
firefox_options.add_argument("-profile")
firefox_options.add_argument("自定义Firefox配置文件的绝对路径")
firefox_options.set_capability("acceptInsecureCerts", True)

driver = webdriver.Firefox(options=firefox_options)

常见适配排查点

  • Geckodriver版本建议选择0.29.0,该版本和Firefox 85.0.1适配性最优,过高版本的Geckodriver会主动重置自定义证书配置,导致弹窗重新出现。
  • 如果目标站点使用HTTP/2协议传输,需要额外补充偏好配置firefox_options.set_preference("network.http.http2.enabled", False),HTTP/2场景下的证书校验优先级高于普通HTTPS校验,会绕过之前的安全配置。
  • 启动前确认目标站点没有触发HSTS强制缓存,HSTS规则会在浏览器端固化高优先级的证书校验逻辑,就算设置了接受不受信任证书的配置,也会触发告警页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 23:57:03