是否可以使用Python / BeautifulSoup从一大块HTML EXCEPT锚/链接中去除所有标签?

时间:2013-08-03 07:23:31

标签: python html beautifulsoup

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

BeautifulSoup中这可能/简单吗?

1 个答案:

答案 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)