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

使用PyInstaller打包含Playwright Firefox驱动的脚本遇libmozsandbox.so缺失问题

PyInstaller打包Playwright Firefox脚本时libmozsandbox.so找不到的解决办法

问题描述

打包集成Playwright Firefox驱动的Python脚本时,运行生成的可执行文件出现以下错误:

libmozsandbox.so: cannot open shared object file: No such file or directory

最简示例代码:

import time
from playwright.sync_api import sync_playwright, TimeoutError

with sync_playwright() as p:
    browser = p.firefox.launch(headless=True)
    
    context = browser.new_context(
        viewport={"width": 1280, "height": 900}
    )
    page = context.new_page()

    page.goto("https://www.python.org/")
    time.sleep(10)

已尝试的操作:

  • 带/不带--with-deps选项安装Firefox(命令:PLAYWRIGHT_BROWSERS_PATH=0 playwright install firefox)
  • 带/不带PLAYWRIGHT_BROWSERS_PATH=0参数安装Firefox
  • 在.launch()中传入args=['--no-sandbox']启动Firefox

替换为Chromium打包运行一切正常,问题仅针对Firefox。


解决方案

方案1:手动复制Firefox依赖并指定二进制路径

  1. 查看Playwright安装的Firefox路径:

    playwright install --dry-run firefox
    

    输出会显示类似~/.cache/ms-playwright/firefox-xxx/的路径。

  2. 修改脚本,指定Firefox二进制文件相对路径(打包后生效):

    with sync_playwright() as p:
        browser = p.firefox.launch(
            headless=True,
            executable_path="./firefox/firefox"
        )
        # 后续代码不变
    
  3. 打包完成后,将Firefox整个安装目录复制到可执行文件所在目录,并重命名为firefox。

方案2:用PyInstaller的--add-data参数打包Firefox依赖

  1. 打包时添加--add-data参数,将Firefox目录嵌入到打包文件中:

    pyinstaller -y --onefile --add-data "~/.cache/ms-playwright/firefox-xxx/:firefox" tool.py
    

    注意替换xxx为实际的Firefox版本号。

  2. 修改脚本,动态获取打包后的Firefox路径:

    import sys
    import os
    from playwright.sync_api import sync_playwright, TimeoutError
    
    def get_firefox_executable():
        if getattr(sys, 'frozen', False):
            # 打包后的运行环境
            return os.path.join(sys._MEIPASS, 'firefox', 'firefox')
        else:
            # 开发环境
            with sync_playwright() as p:
                return p.firefox.executable_path
    
    with sync_playwright() as p:
        browser = p.firefox.launch(
            headless=True,
            executable_path=get_firefox_executable()
        )
        # 后续代码不变
    

方案3:禁用Firefox沙箱(适合测试/内部场景)

通过设置环境变量和启动参数彻底禁用沙箱,避免依赖libmozsandbox.so:

import os
import time
from playwright.sync_api import sync_playwright, TimeoutError

# 设置环境变量禁用沙箱
os.environ['MOZ_DISABLE_SANDBOX'] = '1'

with sync_playwright() as p:
    browser = p.firefox.launch(
        headless=True,
        args=['--no-sandbox']
    )
    # 后续代码不变

重新打包后运行即可,该方法无需额外复制文件,但会降低浏览器安全性,不建议在生产环境使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:24:50