Python抓取網頁連結__Python

來源:互聯網
上載者:User

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() 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.