[求助] Python 调用 phantomjs 时如何解决因内存溢出(Out of memory)被系统终止的问题


[求助] Python 调用 phantomjs 时如何解决因内存溢出(Out of memory)被系统终止的问题

12 回复

内存太小了?


这个问题我遇到过。PhantomJS 在处理大页面或长时间运行时确实容易内存泄漏,特别是通过 Selenium 调用时。核心是限制页面加载和及时清理。

最直接的解决方案是使用 --max-disk-cache-size--disk-cache 参数,并配合资源限制:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

dcap = DesiredCapabilities.PHANTOMJS
dcap["phantomjs.page.settings.resourceTimeout"] = 10  # 资源加载超时
dcap["phantomjs.page.settings.loadImages"] = False    # 不加载图片

service_args = [
    '--disk-cache=true',
    '--max-disk-cache-size=4096',  # 4MB 磁盘缓存
    '--load-images=false',
    '--ignore-ssl-errors=true'
]

driver = webdriver.PhantomJS(
    desired_capabilities=dcap,
    service_args=service_args
)

# 关键:设置页面大小和超时
driver.set_page_load_timeout(30)
driver.set_script_timeout(30)

try:
    driver.get('your_url')
    # 你的操作代码...
finally:
    driver.quit()  # 必须显式退出释放资源

如果问题依旧,考虑分块处理数据或升级到无头 Chrome。PhantomJS 已经停止维护,内存管理确实不如现代浏览器。

总结:限制资源加载和设置超时是关键。

#1 1.6G 不算小吧,程序启动了可以运行几个小时,内存一直增加,然后就被 kill 了

phantomjs OOM 很正常,用 chrome headless mode。作者都是这样说

为什么不用 chrome headless 呢。

一定要用 phantomjs 的话,可以爬几个页面重启一下 phantomjs

建议使用 chromedriver,phantomjs 就很容易被识别。。。

#3
#4
#6
#7

好吧,看来我用到的工具落后了,已经更换到了 chrome headless,今天跑一跑,看看情况


#5 这个有点麻烦,解决方法不是太优雅

新的就用 chrome headless,老的懒得切就继续 phantomjs 咯

作者不是溜了么。。

chrome 沒有像 phantomjs 那樣的 web server 模塊吧?

#9 个人用,所以切换比较方便

#10 不太清楚呢

#11 我感觉两种方式差不多,chrome 需要一个额外的 chromedriver

回到顶部