我试图在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()
在调用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()
这可能是某种错误吗?