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

Playwright Python启动Firefox设置security.enterprise_roots.enabled遇NS_ERROR_UNKNOWN

解决Playwright Firefox适配企业MITM根CA的问题

在WSL Ubuntu 22.04环境下,使用Python Playwright爬取仅兼容Firefox的公司内网HTTPS门户时,遇到企业MITM代理的证书验证问题:

  • 已在系统中安装公司根CA,但设置Firefox偏好security.enterprise_roots.enabled: "true"启动浏览器时,触发NS_ERROR_UNEXPECTED错误
  • 移除该偏好或设置其他参数时,访问页面会出现SEC_ERROR_UNKNOWN_ISSUER证书验证失败

错误核心原因:security.enterprise_roots.enabled是布尔型配置项,代码中传入字符串"true"会导致Firefox的偏好系统解析失败,抛出错误。


方案1:修正配置项类型

将security.enterprise_roots.enabled的取值改为Python布尔值True,而非字符串:

from playwright.sync_api import sync_playwright

with sync_playwright() as pwobj:
    browser = pwobj.firefox.launch(
        headless=False,
        firefox_user_prefs={
            # 正确传入布尔值,而非字符串形式的"true"
            "security.enterprise_roots.enabled": True
        }
    )
    page = browser.new_page()
    # 测试企业根CA是否生效
    page.goto("https://untrusted-root.badssl.com/")
    print(page.title())
    browser.close()

方案2:手动导入根CA(方案1无效时使用)

如果系统安装的根CA未被Firefox自动识别,可手动将CA证书导入到Playwright使用的Firefox配置:

  1. 导出公司根CA为PEM格式文件(命名为company-root-ca.pem)
  2. 通过Firefox偏好手动添加证书:
from playwright.sync_api import sync_playwright
import base64

# 读取CA证书并编码为base64格式
with open("company-root-ca.pem", "rb") as f:
    ca_cert_b64 = base64.b64encode(f.read()).decode("utf-8")

with sync_playwright() as pwobj:
    browser = pwobj.firefox.launch(
        headless=False,
        firefox_user_prefs={
            "security.enterprise_roots.enabled": True,
            # 手动注入根CA证书
            "security.enterprise_roots.add": ca_cert_b64
        }
    )
    page = browser.new_page()
    page.goto("https://your-internal-portal.com")
    browser.close()

验证方法

运行代码后,若能正常加载目标内网门户,或访问https://untrusted-root.badssl.com/时页面显示"untrusted-root.badssl.com",则说明CA配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:56:00