Ses*_*shu 9 python memory beautifulsoup
我试图在python 2.7.3中使用BeautifulSoup4处理几个网页但是在每次解析之后内存使用量都会上升.
此简化代码产生相同的行为:
from bs4 import BeautifulSoup
def parse():
f = open("index.html", "r")
page = BeautifulSoup(f.read(), "lxml")
f.close()
while True:
parse()
raw_input()
Run Code Online (Sandbox Code Playgroud)
在调用parse()五次后,python进程已经使用了30 MB的内存(使用的HTML文件大约是100 kB),每次调用时它都会增加4 MB.有没有办法释放内存或某种解决方法?
更新: 这种行为让我很头疼.即使应该长时间删除BeautifulSoup变量,此代码也会轻松占用大量内存:
from bs4 import BeautifulSoup
import threading, httplib, gc
class pageThread(threading.Thread):
def run(self):
con = httplib.HTTPConnection("stackoverflow.com")
con.request("GET", "/")
res = con.getresponse()
if res.status == 200:
page = BeautifulSoup(res.read(), "lxml")
con.close()
def load():
t = list()
for i in range(5):
t.append(pageThread())
t[i].start()
for thread in t:
thread.join()
while not raw_input("load? "):
gc.collect()
load()
Run Code Online (Sandbox Code Playgroud)
这可能是某种错误吗?
小智 9
尝试使用Beautiful Soup的分解功能,当您使用完每个文件时,它会破坏树.
from bs4 import BeautifulSoup
def parse():
f = open("index.html", "r")
page = BeautifulSoup(f.read(), "lxml")
# page extraction goes here
page.decompose()
f.close()
while True:
parse()
raw_input()
Run Code Online (Sandbox Code Playgroud)
我知道这是一个旧线程,但是在使用 beautifulsoup 解析页面时还需要记住一件事。导航树时,如果要存储特定值,请确保获取字符串而不是 bs4 对象。例如,在循环中使用时这会导致内存泄漏:
category_name = table_data.find('a').contents[0]
Run Code Online (Sandbox Code Playgroud)
这可以通过更改为来修复:
category_name = str(table_data.find('a').contents[0])
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,类别名称的类型是 bs4.element.NavigableString
尝试垃圾收集:
from bs4 import BeautifulSoup
import gc
def parse():
f = open("index.html", "r")
page = BeautifulSoup(f.read(), "lxml")
page = None
gc.collect()
f.close()
while True:
parse()
raw_input()
Run Code Online (Sandbox Code Playgroud)
也可以看看: