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

Python Playwright持续爬取网站遇JavaScript堆内存溢出问题求助

解决Playwright持续爬取时JavaScript堆内存溢出问题

这个报错是Playwright依赖的Node.js进程V8堆内存耗尽导致的,以下是几种可行的解决方法:

1. 严格清理爬取资源

每次爬取完成后,必须关闭页面、销毁浏览器上下文,避免内存累积。示例代码:

from playwright.sync_api import sync_playwright

def crawl_single_url(url):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        try:
            page.goto(url)
            # 执行你的爬取逻辑,比如提取数据、截图等
            # ...
        finally:
            # 确保资源被正确释放
            page.close()
            context.close()
            browser.close()

# 批量爬取示例
target_urls = ["https://example.com", "https://test.com"]
for url in target_urls:
    crawl_single_url(url)

2. 增大Node.js堆内存限制

Node.js默认堆内存上限不足以支撑长时间爬取,通过设置环境变量调高内存:

  • Windows命令行:
set NODE_OPTIONS=--max-old-space-size=4096 && python your_crawl_script.py
  • Linux/macOS终端:
export NODE_OPTIONS="--max-old-space-size=4096" && python your_crawl_script.py
  • 也可以在Python脚本内提前设置:
import os
os.environ["NODE_OPTIONS"] = "--max-old-space-size=4096"

from playwright.sync_api import sync_playwright
# 后续爬取代码...

注:4096代表4GB内存,可根据你的机器配置调整(比如8GB内存可设为8192)

3. 定期重启浏览器实例

即使清理了页面和上下文,浏览器长时间运行仍可能存在内存泄漏,定期重启可以彻底释放内存:

from playwright.sync_api import sync_playwright
import os

os.environ["NODE_OPTIONS"] = "--max-old-space-size=4096"

# 每爬取N个页面重启一次浏览器
RESET_INTERVAL = 50
task_counter = 0

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    for url in your_url_list:
        task_counter += 1
        context = browser.new_context()
        page = context.new_page()
        try:
            page.goto(url)
            # 爬取逻辑
        finally:
            page.close()
            context.close()
        
        # 达到阈值重启浏览器
        if task_counter % RESET_INTERVAL == 0:
            browser.close()
            browser = p.chromium.launch(headless=True)

4. 排查代码中的内存泄漏点

  • 检查是否有全局变量存储了大量爬取数据、页面元素或响应对象,及时清理无用数据
  • 避免长时间保留Playwright的事件监听器,不用时移除
  • 尽量避免在循环中创建不必要的对象,减少内存占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:18:31