Strip HTML from strings in Python

前端 未结 26 2313
难免孤独
难免孤独 2020-11-22 02:50
from mechanize import Browser
br = Browser()
br.open(\'http://somewebpage\')
html = br.response().readlines()
for line in html:
  print line

When p

26条回答
  •  借酒劲吻你
    2020-11-22 03:19

    A python 3 adaption of søren-løvborg's answer

    from html.parser import HTMLParser
    from html.entities import html5
    
    class HTMLTextExtractor(HTMLParser):
        """ Adaption of http://stackoverflow.com/a/7778368/196732 """
        def __init__(self):
            super().__init__()
            self.result = []
    
        def handle_data(self, d):
            self.result.append(d)
    
        def handle_charref(self, number):
            codepoint = int(number[1:], 16) if number[0] in (u'x', u'X') else int(number)
            self.result.append(unichr(codepoint))
    
        def handle_entityref(self, name):
            if name in html5:
                self.result.append(unichr(html5[name]))
    
        def get_text(self):
            return u''.join(self.result)
    
    def html_to_text(html):
        s = HTMLTextExtractor()
        s.feed(html)
        return s.get_text()
    

提交回复
热议问题