3

我有一大块 HTML,我想剥离所有标签,将其保留为纯文本,除非留在<a href="url">some text<a>链接中。

这在 BeautifulSoup 中可能/简单吗?

4

1 回答 1

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)
于 2013-08-03T07:37:52.193 回答