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

在Google Colab运行Playwright时触发Attempt to free invalid pointer错误

解决Google Colab中Playwright运行"Browser closed"错误

错误原因分析

从日志里的src/tcmalloc.cc:283] Attempt to free invalid pointer可以看出,这是Chromium内存分配相关的崩溃,结合Colab环境特性和你的代码,问题集中在异步代码不规范、环境兼容性和启动参数缺失上。

解决方案

1. 替换同步sleep为异步sleep

在异步函数中使用time.sleep()会阻塞整个事件循环,导致浏览器进程无法正常通信而崩溃,必须换成await asyncio.sleep():

# 替换原代码中的time.sleep
await asyncio.sleep(6)
await asyncio.sleep(5)

2. 检查storage_state文件有效性

如果auth.json文件不存在或格式错误,调用new_page(storage_state='auth.json')会直接导致浏览器启动失败。先注释掉这个参数测试基础功能:

page = await browser.new_page()  # 暂时移除storage_state参数

3. 添加Colab适配的Chromium启动参数

Colab的Linux环境需要额外参数避免Chromium崩溃,在launch()中补充以下参数:

browser = await p.chromium.launch(
    headless=True,
    args=[
        "--disable-gpu",
        "--single-process",
        "--no-zygote",
        "--no-sandbox"  # 保留原有的--no-sandbox参数
    ]
)

4. 升级Python版本(可选但推荐)

Colab默认的Python3.7和部分Playwright Chromium版本存在兼容性问题,可以切换到Python3.8+:

!update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1
!update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
!update-alternatives --config python3

选择Python3.8后重新安装Playwright。

5. 确保正确释放资源

取消注释await browser.close(),避免浏览器进程残留导致后续运行异常。

修改后的完整代码

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            args=["--disable-gpu", "--single-process", "--no-zygote", "--no-sandbox"]
        )
        page = await browser.new_page()
        await page.goto('https://www.google.com')
        await asyncio.sleep(6)
        html = await page.content()
        await asyncio.sleep(5)
        await browser.close()

asyncio.run(main())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:54:33