Python抓取网页链接

http://blog.csdn.net/cscmaker/article/details/8730153

(1)因项目需要,需要从web中抓取相关的网页。正好想学习一下Python,首先看了一下Python简明教程,内容讲的不多,但是能够使你快速入门,我一直认为实例驱动学习是最有效的办法。所以直接通过实际操作怎么去抓取网页来丰富对Python的学习效果会更好。

         Python提供了各种各样的库,使得各种操作变得很方便。这里使用的是Python的urllib2和sgmllib库。为了处理HTML,Python总共提供了三个模块:sgmllib htmllibHTMLParser。本文中采用的是sgmllib,但是通过查找相关资料发现其实第三方工具BeautifulSoup是最好的,能够处理较差的HTML。所以后面还要接着学习BeautifulSoup。

(2)脚本代码

[python]
view plain
copy

  1. class LinksParser(sgmllib.SGMLParser):  
  2.  urls = []  
  3.  def do_a(self, attrs):  
  4.   for name, value in attrs:  
  5.    if name == ‘href’ and value not in self.urls:  
  6.     if value.startswith(‘http’):  
  7.       self.urls.append(value)  
  8.       print value  
  9.     else:  
  10.      continue  
  11.     return  
  12.   
  13. p =  LinksParser()  
  14. f = urllib2.urlopen(‘http://www.baidu.com’)  
  15. #f = urllib2.urlopen(‘https://www.googlestable.com/search?hl=zh-CN&site=&source=hp&q=%E9%BB%84%E6%B8%A4++%E6%B3%B0%E5%9B%A7&btnK=Google+%E6%90%9C%E7%B4%A)  
  16. p.feed(f.read())  
  17. for url in p.urls:  
  18.   print url  
  19. f.close()  
  20. p.close() 
    原文作者:hshl1214
    原文地址: https://blog.csdn.net/hshl1214/article/details/50614520
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞