10

我想知道如何使用BeautifulSoup.

输入:

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

输出:

... text ... text
4

2 回答 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('')- 将产生相同的结果,但看起来更合适。

于 2013-08-26T21:30:46.267 回答
0

这是针对 XML 的,如果您想要针对 HTML,请将导入从更改BeautifulStoneSoupBeautifulSoup

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)
于 2013-08-26T22:07:46.503 回答