gpt4 book ai didi

BeautifulSoup 的 Python 高内存使用率

转载 作者:IT王子 更新时间:2023-10-28 23:34:05 25 4
gpt4 key购买 nike

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

这可能是某种错误吗?

最佳答案

试试美汤的decompose当您处理完每个文件时,会破坏树的功能。

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()

关于BeautifulSoup 的 Python 高内存使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11284643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com