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

Python Playwright中PKCS12格式PFX证书无法加载问题排查

问题代码中的错误及修复方案

核心错误点

  • Firefox不支持直接使用PFX格式证书配置
    Playwright对Firefox的客户端证书配置,要求提供PEM格式的证书文件(.crt/.pem)和密钥文件(.key),而非PFX文件。代码中直接给Firefox配置pfxPath是无效的,这是Chrome/Edge的专属配置方式,Firefox不兼容。

  • 错误的配置位置
    你将client_certificates添加到了预定义的device字典中,这不是正确做法。应该在调用browser.new_context()时单独传入该参数,避免覆盖或干扰设备的默认配置逻辑。

  • 证书转换步骤错误
    当前的openssl命令只是将旧PFX重新打包成新PFX,对Firefox没有帮助。正确的做法是从PFX中提取出PEM格式的证书和密钥文件。

修复步骤及代码示例

1. 正确转换PFX到PEM格式

使用以下openssl命令提取证书和密钥:

# 提取PEM格式证书
openssl pkcs12 -in oldPfxFile.pfx -clcerts -nokeys -out certificate.pem -legacy
# 提取PEM格式密钥(需输入PFX密码)
openssl pkcs12 -in oldPfxFile.pfx -nocerts -out private.key -legacy
# 可选:移除密钥的保护密码(避免每次输入)
openssl rsa -in private.key -out private_nopass.key

2. 修改代码配置

将客户端证书配置从device移到new_context的参数中,使用Firefox支持的certPath和keyPath参数:

import asyncio
from fake_useragent import UserAgent
from playwright.async_api import async_playwright


async def page_launch_playwright():
    playwright = await async_playwright().start()
    device = playwright.devices["Desktop Firefox"]
    device['user_agent'] = UserAgent().firefox
    device['viewport'] = {'width': 1366, 'height': 768}

    url_base_path = "https://website.com"

    launch_config = {
        "headless": False,
        "timeout": 10000.0,
        "proxy": None,
        "slow_mo": 190
    }

    browser = await playwright.firefox.launch(**launch_config)

    # 正确配置Firefox客户端证书
    context = await browser.new_context(
        **device,
        client_certificates=[
            {
                "origin": "https://website.com",
                "certPath": "./certificate.pem",
                "keyPath": "./private_nopass.key",
                # 如果密钥保留了保护密码,添加下面这行
                # "passphrase": "your-key-passphrase"
            }
        ]
    )

    await context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
    page_driver = await context.new_page()
    await page_driver.goto(url_base_path)
    await page_driver.wait_for_timeout(2000.0)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(page_launch_playwright())

3. 额外注意事项

  • 确保证书和密钥文件的路径正确,路径是相对于脚本运行的目录。
  • 如果网站使用子域名,origin需要匹配准确(比如https://sub.website.com),或者使用通配符https://*.website.com。
  • 确认Playwright自动下载的Firefox版本与1.46版本兼容,不要手动替换浏览器文件。

内容的提问来源于stack exchange,提问作者Iron Banker Of Braavos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:56