【python】bs4 删除clear、decompose、extract的区别

333 阅读1分钟
1. clear

清除标签内的内容(包括子标签和文本)

html = "<html><body><p><a></a></p></body></html>"
soup.p.clear()
# <html><body><p></p></body></html>
2. decompose

清除标签(包括该标签)的内容(包括子标签和文本)

html = "<html><body><p><a></a></p></body></html>"
soup.p.decompose()
# <html><body></body></html>
3. extract

清除标签(包括该标签)的内容(包括子标签和文本)并返回
同decompose,但是会返回删除的节点

html = "<html><body><p><a></a></p></body></html>"
p_extract = soup.p.extract()
# <html><body></body></html>
# p_extract:<p><a></a></p>