簡體   English   中英

Python:從文本數據中刪除html

[英]Python: strip html from text data

我的問題與以下內容有些相關: 從Python中的字符串中刪除HTML

我正在尋找一種從文本中刪除HTML代碼的簡單方法。 例如:

string = 'foo <SOME_VALID_HTML_TAG> something </SOME_VALID_HTML_TAG> bar'
stripIt(string)

然后會產生foo bar

有什么簡單的工具可以在Python中實現這一點嗎? HTML代碼可以嵌套。

import lxml.html
import re

def stripIt(s):
    doc = lxml.html.fromstring(s)   # parse html string
    txt = doc.xpath('text()')       # ['foo ', ' bar']
    txt = ' '.join(txt)             # 'foo   bar'
    return re.sub('\s+', ' ', txt)  # 'foo bar'

s = 'foo <SOME_VALID_HTML_TAG> something </SOME_VALID_HTML_TAG> bar'
stripIt(s)

回報

foo bar
from BeautifulSoup import BeautifulSoup

def removeTags(html, *tags):
    soup = BeautifulSoup(html)
    for tag in tags:
        for tag in soup.findAll(tag):
            tag.replaceWith("")

    return soup


testhtml = '''
<html>
    <head>
        <title>Page title</title>
    </head>
    <body>text here<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
        <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
    </body>
</html>'''

print removeTags(testhtml, 'b', 'p')

你可以使用正則表達式:

def stripIt(s):
  txt = re.sub('<[^<]+?>.*?</[^<]+?>', '', s) # Remove html tags
  return re.sub('\s+', ' ', txt)              # Normalize whitespace

但是,我更喜歡Hugh Bothwell的解決方案,因為它比純正則表達式更強大。

如果有人striptags此問題並且已經使用jinja模板語言:您可以在模板中使用過濾器striptags ,並在代碼中使用函數jinja2.filters.do_striptags()

嘗試此解決方案:

from BeautifulSoup import BeautifulSoup

def stripIt(string, tag):
    soup = BeautifulSoup(string)

    rmtags = soup.findAll(tag)
    for t in rmtags:
        string = string.replace(str(t), '')
    return string

string = 'foo <p> something </p> bar'
print stripIt(string, 'p')
>>> foo  bar

string = 'foo <a>bar</a> baz <a>quux</a>'
print stripIt(string, 'a')
>>> foo  baz

編輯:這僅適用於有效嵌套標記,例如:

string = 'blaz <div>baz <div>quux</div></div>'
print stripIt(string, 'div')
>>> blaz

string = 'blaz <a>baz <a>quux</a></a>'
print stripIt(string, 'a')
>>> blaz <a>baz </a>

您可以通過相應地覆蓋方法來利用HTMLParser:

from HTMLParser import HTMLParser

class HTMLStripper(HTMLParser):

    text_parts = []
    depth = 0

    def handle_data(self, data):
        if self.depth == 0:
            self.text_parts.append(data.strip())

    def handle_charref(self, ref):
        data = unichr(int(ref))
        self.handle_data(data)

    def handle_starttag(self, tag, attrs):
        self.depth += 1

    def handle_endtag(self, tag):
        if self.depth > 0:
            self.depth -= 1

    def handle_entityref(self, ref):
        try:
            data = unichr(name2codepoint[ref])
            self.handle_data(data)
        except KeyError:
            pass

    def get_stripped_text(self):
        return ' '.join(self.text_parts)

def strip_html_from_text(html):
    parser = HTMLStripper()
    parser.feed(html)
    return parser.get_stripped_text()

def main():
    import sys
    html = sys.stdin.read()
    text = strip_html_from_text(html)
    print text

if __name__ == '__main__':
    main() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM