从文本中删除所有HTML标签及其内容

10

我想知道如何使用BeautifulSoup删除所有HTML标签及其内容。

输入:

... text <strong>ha</strong> ... text

输出:

... text ... text

但是,如果你从一个HTML文档中删除所有的HTML标签,最后你只会得到一个空字符串。你只想要删除_特定_的标签吗?还是要删除某个顶层标签内的所有标签? - abarnert
一个更Pythonic的答案可能是这个:https://dev59.com/6m035IYBdhLWcg3wJccw - Christos Papoulas
2个回答

20
使用 replace_with()(或replaceWith())函数:
from bs4 import BeautifulSoup, Tag


text = "text <strong>ha</strong> ... text"

soup = BeautifulSoup(text)

for tag in soup.find_all('strong'):
    tag.replaceWith('')

print soup.get_text() 

输出:

text  ... text

或者,正如 @mata 建议的那样,你可以使用 tag.decompose() 代替 tag.replaceWith('') - 这将产生相同的结果,但看起来更合适。


7
"decompose"可能是更合适的选择。 - mata
@mata:你应该把它写成一个单独的答案。 - abarnert
@alecxe 标签不一定是 <strong>。 - Adam
我也不明白,我该如何获取结果?tag.replaceWith('') 没有分配任何内容。 - Adam
@AdamSilver 它可以代替 soup 对象。使用 get_text() 获取结果。 - alecxe

0
这是针对XML的,如果你想用于HTML,请将导入从BeautifulStoneSoup改为BeautifulSoup
try:
    #Using bs4
    from bs4 import BeautifulStoneSoup
    from bs4 import Tag
except ImportError:
    #Using bs3
    from BeautifulSoup import BeautifulStoneSoup
    from BeautifulSoup import Tag

def info_extract(isoup):
    '''
    Recursively walk a nested list and upon finding a non iterable, return its string
    '''
    tlist = []
    def info_extract_helper(inlist, count = 0):
        if(isinstance(inlist, list)):
            for q in inlist:
                if(isinstance(q, Tag)):
                    info_extract_helper(q.contents, count + 1)
                else:
                    extracted_str = q.strip()
                    if(extracted_str and (count > 1)):
                        tlist.append(extracted_str)
    info_extract_helper([isoup])
    return tlist

xml_str = \
'''
<?xml version="1.0" encoding="UTF-8"?>
    <first-tag>
      <second-tag>
        <events-data>
           <event-date someattrib="test">
                <date>20040913</date>
           </event-date>
        </events-data>

      <events-data>
         <event-date>
           <date>20040913</date>
         </event-date>
      </events-data> 
     </second-tag>
   </first-tag>
'''

soup = BeautifulStoneSoup(xml_str)
print info_extract(soup)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接