Python网络编程测试-HTML解析


Python提供了一个HTMLParser的模块,当然现在web page通常都多多少少存在HTML不规范的问题,比如说<p>但是并没有关闭(也就是说没有</p>,虽然XHTML可以避免这种事情的发生),mxTidy , 和uTidylib通常可以完成HTML正规化的处理工作。
似乎在解析HTML时,正则表达式就不是那么有力的工具了。还是使用Python提供的模块和工具比较方便
下面的code定义了一个从HTMLParser继承而来的TiTleParser类,通过该对象对标签<title></title>进行“识别”和解析。
[python]
#test of the parsing the HTML and XML 
 
import sys , urllib2 
from HTMLParser import HTMLParser 
 
class TitleParser(HTMLParser): 
  def __init__(self): 
    self.title = '' 
    self.readingtitle = 0 
    HTMLParser.__init__(self) 
 
  def handle_starttag(self , tag , attrs): 
    if tag == 'title': 
      self.readingtitle = 1 
  def handle_data(self , data): 
    if self.readingtitle: 
      self.title += data 
  def handle_endtag(self , tag): 
    if tag == 'title': 
      self.readingtitle = 0 
  def gettitle(self): 
    return self.title 
 
def parseHTMLTitle(): 
  
  print('choose the file address: ') 
  addr = sys.stdin.readline().rstrip() 
   
  if(addr == 'url'): 
    print('input the url address:') 
  elif(addr == 'local'): 
    print('input the local filename: ') 
  else: 
    print('input the right method') 
   
  filename = sys.stdin.readline().rstrip() 
 
  if(addr == 'url'): 
    fd = urllib2.urlopen(filename) 
  elif(addr == 'local'): 
    fd = open(filename) 
  else: 
    print('filename wrong') 
 
  tp = TitleParser() 
  tp.feed(fd.read()) 
  print('the title is: ' , tp.gettitle().strip()) 

上面code中并不包涵实体翻译功能,所以在通过urlopen方法打开web page时会存在实体消失或其他相关问题(本人认为是这样,还望牛人指教)
结果:


\






摘自 FishinLab的专栏

相关内容

    暂无相关文章

评论关闭