我有一大块HTML,我想剥离所有标签,将其保留为明文,除非留在<a href="url">some text<a>
链接中。
BeautifulSoup中这可能/简单吗?
答案 0 :(得分:3)
试试这个。
import BeautifulSoup
doc = '''<html><head><title>Page title</title></head><body><p id="firstpara" align="center">This is <i>paragraph</i> <a onclick="">one</a>.<p id="secondpara" align="blah">This is <i>paragraph</i> <b>two</b>.</html>'''
soup = BeautifulSoup.BeautifulSoup(doc)
for tag in soup.recursiveChildGenerator():
if isinstance(tag,BeautifulSoup.Tag) and tag.name not in ('a'):
print(tag.string)
elif isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a'):
print(tag)