Skip to main content
 首页 » 编程设计

python之用 BeautifulSoup 抓取不同的元素 : avoid duplicating in nested elements

2025年05月04日9exmyth

我想使用 BeautifulSoup4 从本地保存的网站(python 文档)中获取不同的内容(类),所以我使用这段代码(index.html 是这个保存的网站:https://docs.python.org/3/library/stdtypes.html)

from bs4 import BeautifulSoup 
soup = BeautifulSoup(open("index.html")) 
f = open('test.html','w') 
f.truncate 
classes= soup.find_all('dl', attrs={'class': ['class', 'method','function','describe', 'attribute', 'data', 'clasmethod', 'staticmethod']}) 
print(classes,file=f)  
f.close() 

文件处理程序仅用于结果输出,对问题本身没有影响。

我的问题是结果是嵌套的。例如,方法“__eq__ (exporter) 将在 1. 类内部和 2. 作为独立方法找到。

所以我想删除其他结果中的所有结果,以使每个结果都处于同一层次结构级别。我怎样才能做到这一点?或者甚至可以在第一步中“忽略”该内容?我希望你明白我的意思。

请您参考如下方法:

你不能告诉 find 忽略嵌套的 dl 元素;您所能做的就是忽略 .descendants 中出现的匹配项:

matches = [] 
for dl in soup.find_all('dl', attrs={'class': ['class', 'method','function','describe', 'attribute', 'data', 'clasmethod', 'staticmethod']}) 
    if any(dl in m.descendants for m in matches): 
        # child of already found element 
        continue 
    matches.append(dl) 

如果你想要嵌套元素并且没有父元素,使用:

matches = [] 
for dl in soup.find_all('dl', attrs={'class': ['class', 'method','function','describe', 'attribute', 'data', 'clasmethod', 'staticmethod']}) 
    matches = [m for m in matches if dl not in m.descendants] 
    matches.append(dl) 

如果你想拆开树并从树中移除元素,使用:

matches = soup.find_all('dl', attrs={'class': ['class', 'method','function','describe', 'attribute', 'data', 'clasmethod', 'staticmethod']}) 
for element in matches: 
    element.extract()  # remove from tree (and parent `dl` matches) 

但您可能想改为调整文本提取。