在實現爬蟲任務時,經常需要將一些圖片下載到本地當中。那麼在python中除了通過open()函數
,以二進制寫入方式來下載圖片以外,還有什麼其他方式嗎?本文將使用urlretrieve
實現直接遠程下載圖片。
代碼實現
在python中除了使用open()函數
實現圖片的下載,還可以通過urllib.request模塊
中的urlretrieve
實現直接遠程下載圖片的操作。以遠程下載某網頁外設產品圖片爲例,代碼如下:
import requests
import urllib.request
import os # 系統模塊
import shutil # 文件夾控制
def download_pictures(url):
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"}
response = requests.get(url, headers=headers) # 發送網絡請求 獲取響應
if response.status_code == 200: # 判斷請求是否成功
# print(response.json())
# 每次獲取數據之前,先將保存圖片的文件夾清空 在創建目錄
if os.path.exists("img_download"): # 判斷文件夾是否存在
shutil.rmtree("img_download") # 存在則刪除
os.makedirs("img_download") # 重新創建
else:
os.makedirs("img_download") # 不存在 直接創建
content = response.json()["products"] # 獲取響應內容
print(content)
for index, item in enumerate(content):
# 圖片地址
img_path = "http://img13.360buyimg.com/n1/s320x320_" + item["imgPath"]
# print(item["imgPath"])
# 根據下標命名圖片名稱
urllib.request.urlretrieve(img_path, "img_download/" + "img" + str(index) + ".jpg")
else:
print("請求失敗")
if __name__ == '__main__':
download_pictures("https://ch.jd.com/hotsale2?cateid=686")
運行結果如下圖所示: