溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python如何寫出最簡單的網(wǎng)頁爬蟲

發(fā)布時間:2021-10-26 17:22:21 來源:億速云 閱讀:131 作者:柒染 欄目:編程語言

Python如何寫出最簡單的網(wǎng)頁爬蟲,針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

最近對python爬蟲有了強烈地興趣,在此分享自己的學(xué)習(xí)路徑。

1.開發(fā)工具

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

sublime text3搭建python開發(fā)環(huán)境推薦查看此博客:

[sublime搭建python開發(fā)環(huán)境][http://www.cnblogs.com/codefish/p/4806849.html]

2.爬蟲介紹

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

既然要爬在Internet上,那么我們就需要了解URL,法號“統(tǒng)一資源定位器”,小名“鏈接”。其結(jié)構(gòu)主要由三部分組成:

(1)協(xié)議:如我們在網(wǎng)址中常見的HTTP協(xié)議。

(2)域名或者IP地址:域名,如:www.baidu.com,IP地址,即將域名解析后對應(yīng)的IP。

(3)路徑:即目錄或者文件等。

3.urllib開發(fā)最簡單的爬蟲

(1)urllib簡介

ModuleIntroduce
urllib.errorException classes raised by urllib.request.
urllib.parseParse URLs into or assemble them from components.
urllib.requestExtensible library for opening URLs.
urllib.responseResponse classes used by urllib.
urllib.robotparserLoad a robots.txt file and answer questions about fetchability of other URLs.

(2)開發(fā)最簡單的爬蟲

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

爬蟲代碼如下:

from urllib import request  def 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()

結(jié)果如下圖:

Python如何寫出最簡單的網(wǎng)頁爬蟲

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

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

代碼如下:

from urllib import request  def 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()

運行結(jié)果和剛才相同。

(3)錯誤處理

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

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

處理HTTPError的代碼如下:

from urllib import request from urllib import error  def 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()

運行結(jié)果如圖:

Python如何寫出最簡單的網(wǎng)頁爬蟲

404為打印出的錯誤代碼,關(guān)于此詳細信息大家可以自行百度。

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

chuliHTTPError的代碼如下:

from urllib import request from urllib import error  def 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()

運行結(jié)果如圖:

Python如何寫出最簡單的網(wǎng)頁爬蟲

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

代碼如下:

from urllib import request from urllib import error  # ***種方法,URLErroe和HTTPError def 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)

大家可以更改url來查看各種錯誤的輸出形式。

關(guān)于Python如何寫出最簡單的網(wǎng)頁爬蟲問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI