本文通過python 來實現這樣一個簡單的爬蟲功能,把我們想要的圖片爬取到本地。
下面就看看如何使用python來實現這樣一個功能。
# -*- coding: utf-8 -*- import urllib import re import time import os #顯示下載進度 def schedule(a,b,c): ''''' a:已經下載的數據塊 b:數據塊的大小 c:遠程文件的大小 ''' per = 100.0 * a * b / c if per > 100 : per = 100 print '%.2f%%' % per def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def downloadImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre, html) #定義文件夾的名字 t = time.localtime(time.time()) foldername = str(t.__getattribute__("tm_year"))+"-"+str(t.__getattribute__("tm_mon"))+"-"+str(t.__getattribute__("tm_mday")) picpath = 'D:\\ImageDownload\\%s' % (foldername) #下載到的本地目錄 if not os.path.exists(picpath): #路徑不存在時創建一個 os.makedirs(picpath) x = 0 for imgurl in imglist: target = picpath+'\\%s.jpg' % x print 'Downloading image to location: ' + target + '\nurl=' + imgurl image = urllib.urlretrieve(imgurl, target, schedule) x += 1 return image; if __name__ == '__main__': print ''' ************************************* ** Welcome to use Spider ** ** Created on 2014-05-13 ** ** @author: cruise ** *************************************''' html = getHtml("http://tieba.baidu.com/p/2460150866") downloadImg(html) print "Download has finished."
這里的核心是用到了urllib.urlretrieve()方法,直接將遠程數據下載到本地。
下面我們再來看看 urllib 模塊提供的 urlretrieve() 函數。urlretrieve() 方法直接將遠程數據下載到本地。
1>>> help(urllib.urlretrieve) 2 Help on function urlretrieve in module urllib: 3 4 urlretrieve(url, filename=None, reporthook=None, data=None)
參數 reporthook 是一個回調函數,當連接上服務器、以及相應的數據塊傳輸完畢時會觸發該回調,我們可以利用這個回調函數來顯示當前的下載進度。
參數 data 指 post 到服務器的數據,該方法返回一個包含兩個元素的(filename, headers)元組,filename 表示保存到本地的路徑,header 表示服務器的響應頭。
通過一個for循環對獲取的圖片連接進行遍歷,為了使圖片的文件名看上去更規范,對其進行重命名,命名規則通過x變量加1。保存的位置默認為程序的存放目錄。
在python shell中看到的信息如下:
程序運行完成,將在目錄下看到下載到本地的文件。