python 解析url

This item was filled under [ 一步一步学习中 ]

摘录了dive into python的例子

Python代码
  1. #-*-coding:utf-8-*-
  2. import HTMLParser
  3. #html解析,继承HTMLParser类
  4. class MyHTMLParser(HTMLParser.HTMLParser):
  5. def _init(self):
  6. HTMLParser.HTMLParser.__init__(self);
  7. # 处理开始标签和结束标签 – finish processing of start+end tag: <tag…/>
  8. def handle_startendtag(self, tag, attrs):
  9. self.handle_starttag(tag, attrs)
  10. self.handle_endtag(tag)
  11. #handle start tag
  12. #处理开始标签和结束标签 这里打印出a标签的href的属性值
  13. def handle_starttag(self,tag, attrs):
  14. if tag==‘a’:
  15. for name,value in attrs:
  16. if name==‘href’:
  17. print value
  18. # 处理结束标签,比如</xx> – handle end tag
  19. def handle_endtag(self,tag):
  20. pass;
  21. # 处理特殊字符串,就是以&#开头的,一般是内码表示的字符 – handle character reference
  22. def handle_charref(self, name):
  23. pass
  24. # 处理一些特殊字符,以&开头的,比如 &nbsp; – handle entity reference
  25. def handle_entityref(self, name):
  26. pass
  27. # 处理数据,就是<xx>data</xx>中间的那些数据 – handle data
  28. def handle_data(self, data):
  29. pass
  30. # 处理注释 – handle comment
  31. def handle_comment(self, data):
  32. pass
  33. # 处理<!开头的,比如<!DOCTYPE html PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN” – handle declaration
  34. def handle_decl(self, decl):
  35. pass
  36. # 处理形如<?instruction>的东西 – handle processing instruction
  37. def handle_pi(self, data):
  38. pass
  39. a=‘<body><a href=”www.163.com”>test</a></body>’
  40. print a
  41. my=MyHTMLParser()
  42. my.feed(a)
  43. #结果为www.163.com
Bookmark and Share
Tagged with: [ ]