參考書籍:《用 Python 寫網(wǎng)絡(luò)爬蟲(chóng)》
下載地址: http://download.csdn.net/detail/wangs0622/9921704
當(dāng)然你也可以自己百度搜索下載姥卢。
一點(diǎn)感想
書看一遍是不夠的,溫故而知新。
下載一個(gè)網(wǎng)頁(yè)源代碼
最簡(jiǎn)單的形式
使用的是 python 自帶的庫(kù) urllib2
import urllib2
def download(url):
print "downloading " , url
html = urllib2.urlopen(url).read()
return html
給定想要下載的 URL 即可下載其源代碼。
添加處理異常的功能
當(dāng)然很有可能在下載的過(guò)程中出現(xiàn)各種問(wèn)題,導(dǎo)致出現(xiàn)問(wèn)題,所以需要在上面的程序上擴(kuò)展,處理異常的情況薪前。
import urllib2
def download(url):
print "downloading " , url
try:
html = urllib2.urlopen(url).read()
except urllib2.URLErrors as e:
print "download error: " , e.reason
html = None
return html
完整的程序如下:
# _*_ encoding:utf-8 _*_
'''
Created on 2017年8月4日
@author: wangs0622
'''
import urllib2
def download(url):
print "downloading " , url
try:
html = urllib2.urlopen(url).read()
except urllib2.URLError as e:
print "download error: " , e.reason
html = None
return html
if __name__ == '__main__':
download('http://www.wangs0622.com/dex')
運(yùn)行的結(jié)果如下:
downloading http://www.wangs0622.com/dex
download error: Not Found
添加重試下載功能
有的時(shí)候,下載出現(xiàn)了問(wèn)題关斜,可能是但是網(wǎng)絡(luò)不好的原因示括,也有可能是頁(yè)面不存在的原因,一般會(huì)返回 4xx 和 5xx 類型的錯(cuò)誤代碼痢畜。 最常見(jiàn)的莫過(guò)于 404垛膝,即表示網(wǎng)頁(yè)未找到。(為什么網(wǎng)頁(yè)為找到丁稀,使用的是 404 代碼呢吼拥? 據(jù)說(shuō)是有歷史原因的,有興趣的話可以去百度线衫。)
正常情況下凿可,返回 5xx 錯(cuò)誤代碼的話,是因?yàn)榫W(wǎng)絡(luò)的原因授账,并不是網(wǎng)頁(yè)不存在枯跑,這個(gè)時(shí)候,我們可以嘗試重新下載這個(gè)網(wǎng)頁(yè)白热,所以敛助,就有了如下的改進(jìn)版本。
import urllib2
def download(url, num_retries = 5):
'''
function: 下載網(wǎng)頁(yè)源代碼屋确,如果遇到 5xx 錯(cuò)誤狀態(tài)辜腺,則繼續(xù)嘗試下載,知道下載 5 次為止乍恐。
'''
print "downloading " , url
try:
html = urllib2.urlopen(url).read()
except urllib2.URLError as e:
print "download error: " , e.reason
html = None
if num_retries > 0:
if hasattr(e,'code') and 500 <= e.code < 600:
return download(url, num_retries-1)
return html
一個(gè)有用的網(wǎng)站
一個(gè)有用的網(wǎng)站: http://httpstat.us/ 專門用來(lái)返回相應(yīng)的網(wǎng)頁(yè)返回代碼。 例如 http://httpstat.us/404
小結(jié)
截止目前的 download() 函數(shù)已經(jīng)具備健全的下載網(wǎng)頁(yè)源代碼的功能测砂,可以應(yīng)付一般情況下的使用了茵烈。
后面還需要介紹為 download() 函數(shù)添加代理和下載延時(shí)功能,之后再介紹 鏈接爬蟲(chóng)砌些。我想法是在介紹這些功能的同時(shí)我們實(shí)踐爬取一個(gè)網(wǎng)站呜投。相信學(xué)爬蟲(chóng)的都是廣大男士加匈,后面實(shí)踐爬取的網(wǎng)站是:http://www.mm131.com 我們的目標(biāo)是將其中的圖片下載下來(lái)。