python之網頁爬蟲教程

來源:互聯網
上載者:User
在我們日常上網瀏覽網頁的時候,經常會看到一些好看的圖片,我們就希望把這些圖片儲存下載,或者使用者用來做案頭壁紙,或者用來做設計的素材。下面這篇文章就來給大家介紹了關於利用python實現最簡單的網頁爬蟲的相關資料,需要的朋友可以參考借鑒,下面來一起看看吧。

前言

網路爬蟲(又被稱為網頁蜘蛛,網路機器人,在FOAF社區中間,更經常的稱為網頁追逐者),是一種按照一定的規則,自動地抓取全球資訊網資訊的程式或者指令碼。最近對python爬蟲有了強烈地興趣,在此分享自己的學習路徑,歡迎大家提出建議。我們相互交流,共同進步。話不多說了,來一起看看詳細的介紹:

1.開發工具

筆者使用的工具是sublime text3,它的短小精悍(可能男人們都不喜歡這個詞)使我十分著迷。推薦大家使用,當然如果你的電腦配置不錯,pycharm可能更加適合你。

sublime text3搭建python開發環境推薦查看這篇文章:

[sublime搭建python開發環境][http://www.jb51.net/article/51838.htm]

2.爬蟲介紹

爬蟲顧名思義,就是像蟲子一樣,爬在Internet這張大網上。如此,我們便可以擷取自己想要的東西。

既然要爬在Internet上,那麼我們就需要瞭解URL,法號“統一資源定位器”,小名“連結”。其結構主要由三部分組成:

(1)協議:如我們在網址中常見的HTTP協議。

(2)網域名稱或者IP地址:網域名稱,如:www.baidu.com,IP地址,即將網域名稱解析後對應的IP。

(3)路徑:即目錄或者檔案等。

3.urllib開發最簡單的爬蟲

(1)urllib簡介

Module Introduce
urllib.error Exception classes raised by urllib.request.
urllib.parse Parse URLs into or assemble them from components.
urllib.request Extensible library for opening URLs.
urllib.response Response classes used by urllib.
urllib.robotparser Load a robots.txt file and answer questions about fetchability of other URLs.

(2)開發最簡單的爬蟲

百度首頁簡潔大方,很適合我們爬蟲。

爬蟲代碼如下:


from urllib import requestdef visit_baidu(): URL = "http://www.baidu.com" # open the URL req = request.urlopen(URL) # read the URL  html = req.read() # decode the URL to utf-8 html = html.decode("utf_8") print(html)if __name__ == '__main__': visit_baidu()

結果如:


我們可以通過在百度首頁空白處右擊,查看審查元素來和我們的運行結果對比。

當然,request也可以產生一個request對象,這個對象可以用urlopen方法開啟。

代碼如下:


from urllib import requestdef vists_baidu(): # create a request obkect req = request.Request('http://www.baidu.com') # open the request object response = request.urlopen(req) # read the response  html = response.read() html = html.decode('utf-8') print(html)if __name__ == '__main__': vists_baidu()

運行結果和剛才相同。

(3)錯誤處理

錯誤處理通過urllib模組來處理,主要有URLError和HTTPError錯誤,其中HTTPError錯誤是URLError錯誤的子類,即HTTRPError也可以通過URLError捕獲。

HTTPError可以通過其code屬性來捕獲。

處理HTTPError的代碼如下:


from urllib import requestfrom urllib import errordef Err(): url = "https://segmentfault.com/zzz" req = request.Request(url) try: response = request.urlopen(req) html = response.read().decode("utf-8") print(html) except error.HTTPError as e: print(e.code)if __name__ == '__main__': Err()

運行結果

404為列印出的錯誤碼,關於此詳細資料大家可以自行百度。

URLError可以通過其reason屬性來捕獲。

chuliHTTPError的代碼如下:


from urllib import requestfrom urllib import errordef Err(): url = "https://segmentf.com/" req = request.Request(url) try: response = request.urlopen(req) html = response.read().decode("utf-8") print(html) except error.URLError as e: print(e.reason)if __name__ == '__main__': Err()

運行結果


既然為了處理錯誤,那麼最好兩個錯誤都寫入代碼中,畢竟越細緻越清晰。須注意的是,HTTPError是URLError的子類,所以一定要將HTTPError放在URLError的前面,否則都會輸出URLError的,如將404輸出為Not Found。

代碼如下:


from urllib import requestfrom urllib import error# 第一種方法,URLErroe和HTTPErrordef Err(): url = "https://segmentfault.com/zzz" req = request.Request(url) try: response = request.urlopen(req) html = response.read().decode("utf-8") print(html) except error.HTTPError as e: print(e.code) except error.URLError as e: print(e.reason)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.