【发布时间】:2015-04-24 15:33:49
【问题描述】:
我基本上和这里的人有同样的问题:Python high memory usage with BeautifulSoup
我的 BeautifulSoup 对象没有被垃圾回收,导致大量的 RAM 消耗。这是我使用的代码(“entry”是我从 RSS 网页获取的对象。它基本上是一篇 RSS 文章)。
title = entry.title
date = arrow.get(entry.updated).format('YYYY-MM-DD')
try:
url = entry.feedburner_origlink
except AttributeError:
url = entry.link
abstract = None
graphical_abstract = None
author = None
soup = BeautifulSoup(entry.summary)
r = soup("img", align="center")
print(r)
if r:
graphical_abstract = r[0]['src']
if response.status_code is requests.codes.ok:
soup = BeautifulSoup(response.text)
# Get the title (w/ html)
title = soup("h2", attrs={"class": "alpH1"})
if title:
title = title[0].renderContents().decode().lstrip().rstrip()
# Get the abstrat (w/ html)
r = soup("p", xmlns="http://www.rsc.org/schema/rscart38")
if r:
abstract = r[0].renderContents().decode()
if abstract == "":
abstract = None
r = soup("meta", attrs={"name": "citation_author"})
if r:
author = [tag['content'] for tag in r]
author = ", ".join(author)
所以在文档 (http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Improving%20Memory%20Usage%20with%20extract) 中,他们说问题可能来自这样一个事实:只要您使用汤对象中包含的标签,汤对象就会保留在内存中。所以我尝试了类似的方法(每次我在前面的例子中使用一个汤对象):
r = soup("img", align="center")[0].extract()
graphical_abstract = r['src']
但是,当程序退出作用域时,内存并没有被释放。
所以,我正在寻找一种从内存中删除汤对象的有效方法。 你有什么想法吗?
【问题讨论】:
-
你试过lxml吗?是
iterparse对于大文档的解析非常高效,看看here -
我知道 lxml,但我更喜欢 BeautifulSoup。我有一个用 BS 编码的完整模块。它可以工作,除了内存泄漏部分。
标签: python memory-leaks beautifulsoup