相关疑难解决方法(0)

使用BeautifulSoup的Python高内存使用率

我试图在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)

这可能是某种错误吗?

python memory beautifulsoup

9
推荐指数
3
解决办法
6073
查看次数

标签 统计

beautifulsoup ×1

memory ×1

python ×1