gpt4 book ai didi

python - 优化 BeautifulSoup (Python) 代码

转载 作者:太空狗 更新时间:2023-10-30 01:03:59 24 4
gpt4 key购买 nike

我有使用 BeautifulSoup 库进行解析的代码,但速度很慢。代码的编写方式无法使用线程。谁能帮我解决这个问题?

我正在使用 BeautifulSoup 进行解析,然后保存到数据库中。如果我注释掉save语句,还是需要很长时间,所以数据库没有问题。

def parse(self,text):                
soup = BeautifulSoup(text)
arr = soup.findAll('tbody')

for i in range(0,len(arr)-1):
data=Data()
soup2 = BeautifulSoup(str(arr[i]))
arr2 = soup2.findAll('td')

c=0
for j in arr2:
if str(j).find("<a href=") > 0:
data.sourceURL = self.getAttributeValue(str(j),'<a href="')
else:
if c == 2:
data.Hits=j.renderContents()

#and few others...

c = c+1

data.save()

有什么建议吗?

注意:我已经问过这个问题here但由于信息不完整,该网站已关闭。

最佳答案

soup2 = BeautifulSoup(str(arr[i]))
arr2 = soup2.findAll('td')

不要这样做:只需调用 arr2 = arr[i].findAll('td') 即可。


这也会很慢:

if str(j).find("<a href=") > 0:
data.sourceURL = self.getAttributeValue(str(j),'<a href="')

假设 getAttributeValue 为您提供了 href 属性,请改用它:

a = j.find('a', href=True)       #find first <a> with href attribute
if a:
data.sourceURL = a['href']
else:
#....

一般来说,如果您只想解析 BeautifulSoup 对象并提取值,则无需将其转换回字符串。由于 findfindAll 方法返回可搜索的对象,您可以通过调用 find/findAll 继续搜索/ETC。结果的方法。

关于python - 优化 BeautifulSoup (Python) 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2712498/

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