示例
如下代码,只提取div里的文本,不提取span里的文本
from bs4 import BeautifulSoup
s='''
<div>
<span> 添加时间:</span>
" 26分钟前"
<br>
<span> 作者:</span>
" 陈冠希"
<br>
</div>
'''
soup=BeautifulSoup(s,'html5lib')
div=soup.find('div')
print([text.strip() for text in div.find_all(text=True) if text.parent.name !='span' and text.strip()])
输出结果

网友评论