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 class LinksParser(sgmllib.SGMLParser): urls = [] def do_a(self, attrs): for name, value in attrs: if name == 'href' and value not in self.urls: if value.startswith('http'): self.urls.append(value) print value else: continue return p = LinksParser() f = urllib2.urlopen('http://www.baidu.com') #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) p.feed(f.read()) for url in p.urls: print url f.close() p.close()