Python 网络编程测试-HTML解析

Python提供了一个HTMLParser的模块,当然现在web page通常都多多少少存在HTML不规范的问题,比如说<p>但是并没有关闭(也就是说没有</p>,虽然XHTML可以避免这种事情的发生),mxTidy , 和uTidylib通常可以完成HTML正规化的处理工作。

似乎在解析HTML时,正则表达式就不是那么有力的工具了。还是使用Python提供的模块和工具比较方便

下面的code定义了一个从HTMLParser继承而来的TiTleParser类,通过该对象对标签<title></title>进行“识别”和解析。

#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时会存在实体消失或其他相关问题(本人认为是这样,还望牛人指教)

结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值