python2
+ 修改基礎存儲路徑
+ 給map裏面添加源url和存儲文件夾,k-v對。
# -*- coding: utf-8 -*- import re import urllib import urllib2 import os # 抓取網頁圖片 # 根據給定的網址來獲取網頁詳細信息,得到的html就是網頁的源代碼 def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def saveImages(imglist, storeFilePath): number = 1 for imageURL in imglist: splitPath = imageURL.split('//') wwwUrl = splitPath.pop() splitPath2 = wwwUrl.split('/') picName = splitPath2.pop() fileName = storeFilePath + picName # 對於每張圖片地址,進行保存 try: u = urllib2.urlopen(imageURL) data = u.read() f = open(fileName, 'wb+') f.write(data) print '正在保存的一張圖片:', fileName f.close() except urllib2.URLError as e: print(e.reason) number += 1 # 獲取網頁中所有圖片的地址 def getAllImg(html): # 利用正則表達式把源代碼中的圖片地址過濾出來 reg = r'href="(.+?\.jpg)"' # https://www.ghibli.jp/gallery/thumb-laputa001.png imgre = re.compile(reg) imglist = imgre.findall(html) # 表示在整個網頁中過濾出所有圖片的地址,放在imglist中 return imglist # 創建本地保存文件夾,並下載保存圖片 if __name__ == '__main__': baseFilePath = '/Users/shaopengyang/pic/' map = { "https://www.ghibli.jp/works/umi/#frame":'umi', "https://www.ghibli.jp/works/majo/#frame":'majo', "https://www.ghibli.jp/works/howl/#frame":'howl'} for url, filePath in map.items(): html = getHtml(url) imgList = getAllImg(html) # 判斷存儲路徑是否存在 isExists = os.path.exists(baseFilePath + filePath + '/') if not isExists: os.makedirs(baseFilePath + filePath + '/') saveImages(imgList, baseFilePath + filePath + '/')