話很少說,直接上代碼;函數
# 須要的庫 import requests import re import os from multiprocessing import Pool # 請求頭 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } # 主函數 def get_img(url): # 定義圖片存儲路徑 img_path = './img/' if not os.path.exists(img_path): os.mkdir(img_path) try: # 請求網頁 response = requests.get(url=url,headers=headers) # 正則提取圖片地址 response = re.findall('<div class="thumb".*?<img src="(.*?)".*?</a>',response.text,re.S) # 循環圖片地址 for i in response: # 拼接完整圖片路由 url = ('http:' + i) # 請求完整圖片路由 response = requests.get(url,headers) # 圖片命名 img_name = url.split('/')[-1] # 判斷圖片是否已下載 if os.path.exists(img_path+img_name): print('圖片已存在') else: # 下載圖片 with open(img_path+img_name,'wb') as f: f.write(response.content) print('正在下載:'+url) except Exception as e: print(e) # 程序主入口 if __name__ == '__main__': # 構造全部ip地址 urls = ['https://www.qiushibaike.com/imgrank/page/{}/'.format(i) for i in range(1,14)] # 使用多進程 pool = Pool() # 開啓多進程爬取 pool.map(get_img,urls) print('下載完畢')
下載中;url
打開文件夾查看圖片;spa
donecode