實現步驟:
1.下載頁面源碼
2.對頁面進行解析,獲取頁面中所有的圖片路徑
3.下載圖片到指定路徑
代碼實例:
# coding: utf-8 import urllib2 # 該模塊用於打開頁面地址 import urllib # 用於下載圖片(為什么需要同時引進urllib和urllib2,請參考:https://www.cnblogs.com/wly923/archive/2013/05/07/3057122.html) import re # 用於正則表達式 import urlparse # 將src拼接成一個可以直接訪問的圖片地址 import os # 用於指定文件的保存地址 from bs4 import BeautifulSoup # 用於將文檔轉為固定編碼文件,便於從網頁抓取數據 class Downloader(object): def html_download(self, url): # 頁面源碼下載 if url is None: return response = urllib2.urlopen(url) if response.getcode() != 200: # 判斷頁面是否訪問成功 return html_cont = response.read() self.html_parse(url, html_cont) def html_parse(self, url, html_cont): # 源碼解析,提取需要的數據 img_urls = [] if url is None or html_cont is None: return soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8') imgs = soup.find_all('img', src=re.compile("/image/2017index/(.*)")) # 根據src得到所有的img標簽 for img in imgs: new_url = img['src'] # 獲取所有的鏈接 new_full_url = urlparse.urljoin(url, new_url) # 讓new_url按照page_url的格式拼接成一個完整的url img_urls.append(new_full_url) self.img_download(img_urls) def img_download(self, img_urls): # 文件下載保存 if img_urls is None or len(img_urls) == 0: print 'no img can download' return cur_path = os.path.abspath(os.curdir) # 獲取當前絕對路徑 goal_path = cur_path + '\\' + 'imgs' # 想將文件保存的路徑 if not os.path.exists(goal_path): # os.path.isfile('test.txt') 判斷文件夾/文件是否存在 os.mkdir(goal_path) # 創建文件夾 count = 1 # 用於給圖片命名 for img in img_urls: print img urllib.urlretrieve(img, goal_path+'/'+str(count) + '.jpg') # 下載圖片,並進行命名(剛開始寫這句的時候老是報錯,后來才發現沒有用str()進行類型轉換,因為習慣了js的自動轉換的思想,哈哈) count = count+1 if __name__ == '__main__': # 程序運行入口 root_url = 'http://www.quanjing.com/' # 頁面地址 downloader = Downloader() downloader.html_download(root_url)
Bingo, 這樣子就可以把一個頁面所有的美女圖片下載到你的硬盤上啦!