基于htmllib.HTMLParser的html2text

基于htmllib.HTMLParser的html2text

 
  
  
  
  
  1. def html2text(strHtml): 
  2.     """处理html 4.01和部分xhtml 1.0转义字符""" 
  3.     class SimpleParser(htmllib.HTMLParser): 
  4.         def anchor_end(self): 
  5.             if self.anchor: 
  6.                 self.anchor = None 
  7.         def handle_image(self, src, alt, *args): 
  8.             #self.handle_data(alt)  #可以重写为alt属性 
  9.             pass                    #图片替换成空 
  10.         def convert_entityref(self, name): 
  11.             name2codepoint["nbsp"]  = 0x0020 
  12.             name2codepoint["apos"]  = 0x0027 
  13.             if name in name2codepoint and name<256
  14.                 return chr(name2codepoint[name]) 
  15.             else
  16.                 return 
  17.         def convert_charref(self, name): 
  18.             return unichr(int(name)).encode("gb18030")    file = StringIO.StringIO() 
  19.     p = SimpleParser(formatter.AbstractFormatter(formatter.DumbWriter(file))) 
  20.     p.feed(strHtml) 
  21.     p.close() 
  22.     return file.getvalue() 基于htmllib.HTMLParser的html2text

 

你可能感兴趣的:(html,python,爬虫,正文)