Python批量下載圖片的實(shí)現(xiàn)步驟
在Python中批量下載圖片可以通過(guò)以下步驟實(shí)現(xiàn),這里提供一個(gè)完整的代碼示例:
基礎(chǔ)方案:使用requests庫(kù)
import os
import requests
from urllib.parse import urlparse
def download_images(image_urls, save_dir='images'):
"""
批量下載圖片到指定目錄
:param image_urls: 圖片URL列表
:param save_dir: 保存目錄(默認(rèn)保存到當(dāng)前目錄的images文件夾)
"""
# 創(chuàng)建保存目錄
os.makedirs(save_dir, exist_ok=True)
for url in image_urls:
try:
# 發(fā)送HTTP請(qǐng)求
response = requests.get(url, stream=True, timeout=5)
response.raise_for_status() # 檢查請(qǐng)求是否成功
# 提取文件名
parsed_url = urlparse(url)
filename = os.path.basename(parsed_url.path)
if not filename:
filename = f"image_{len(os.listdir(save_dir)) + 1}.jpg"
# 保存文件
filepath = os.path.join(save_dir, filename)
with open(filepath, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
print(f"成功下載: {filename}")
except Exception as e:
print(f"下載失敗 {url} - 錯(cuò)誤: {str(e)}")
# 示例使用
if __name__ == "__main__":
# 從網(wǎng)頁(yè)解析圖片URL(示例)
image_urls = [
"https://example.com/images/cat.jpg",
"https://example.com/images/dog.png",
"https://example.com/images/bird.webp"
]
download_images(image_urls)
進(jìn)階方案:從網(wǎng)頁(yè)批量抓取圖片
from bs4 import BeautifulSoup
import requests
def scrape_images_from_webpage(url, save_dir='images'):
"""從網(wǎng)頁(yè)中抓取所有圖片并下載"""
try:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
image_urls = [img.get('src') for img in img_tags if img.get('src')]
download_images(image_urls, save_dir)
except Exception as e:
print(f"抓取失敗: {str(e)}")
# 示例使用
scrape_images_from_webpage("https://example.com/gallery")
關(guān)鍵點(diǎn)說(shuō)明:
依賴庫(kù)安裝:
pip install requests beautifulsoup4
核心功能:
- 自動(dòng)創(chuàng)建保存目錄
- 智能處理文件名(保留原始文件名或自動(dòng)生成)
- 流式下載避免內(nèi)存溢出
- 完善的錯(cuò)誤處理
擴(kuò)展功能建議:
# 添加多線程加速(使用concurrent.futures)
from concurrent.futures import ThreadPoolExecutor
# 在download_images函數(shù)中替換循環(huán)部分
with ThreadPoolExecutor(max_workers=8) as executor:
executor.map(download_single_image, image_urls)
注意事項(xiàng):
- 遵守網(wǎng)站robots.txt協(xié)議
- 添加User-Agent頭避免被屏蔽
- 添加下載延遲防止IP被封
- 處理不同圖片格式(通過(guò)MIME類型判斷)
完整增強(qiáng)版代碼
import os
import requests
from urllib.parse import urlparse
from concurrent.futures import ThreadPoolExecutor
import time
def download_single_image(url, save_dir):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers, stream=True, timeout=10)
response.raise_for_status()
# 獲取內(nèi)容類型確定擴(kuò)展名
content_type = response.headers.get('content-type')
ext = 'jpg' if 'jpeg' in content_type else content_type.split('/')[-1]
filename = os.path.basename(urlparse(url).path) or f"img_{int(time.time()*1000)}.{ext}"
filepath = os.path.join(save_dir, filename)
with open(filepath, 'wb') as f:
for chunk in response.iter_content(8192):
f.write(chunk)
return True, filename
except Exception as e:
return False, str(e)
def batch_download(image_urls, save_dir='images', max_workers=8, delay=0.5):
os.makedirs(save_dir, exist_ok=True)
success = []
failed = []
def worker(url):
result, info = download_single_image(url, save_dir)
if result:
success.append(info)
else:
failed.append((url, info))
time.sleep(delay) # 避免請(qǐng)求過(guò)載
with ThreadPoolExecutor(max_workers=max_workers) as executor:
executor.map(worker, image_urls)
print(f"\n下載完成!成功: {len(success)} 失敗: {len(failed)}")
return success, failed
# 使用示例
if __name__ == "__main__":
urls = [
"https://example.com/image1.jpg",
"https://example.com/image2.png",
# 添加更多URL...
]
success, failed = batch_download(urls)
print("\n成功下載列表:")
for name in success:
print(f" - {name}")
print("\n失敗列表:")
for url, reason in failed:
print(f" - {url}: {reason}")
最佳實(shí)踐建議:
- 添加代理支持:在requests.get中添加
proxies參數(shù) - 限速功能:使用
time.sleep()控制請(qǐng)求頻率 - 斷點(diǎn)續(xù)傳:通過(guò)檢查文件大小實(shí)現(xiàn)
- 自動(dòng)重試機(jī)制:使用
tenacity庫(kù)實(shí)現(xiàn) - 文件去重:使用哈希值檢查重復(fù)文件
這個(gè)方案提供了從基礎(chǔ)到進(jìn)階的完整實(shí)現(xiàn),用戶可以根據(jù)實(shí)際需求選擇適合的版本。代碼中包含了詳細(xì)的錯(cuò)誤處理和日志輸出,適合直接用于生產(chǎn)環(huán)境。
到此這篇關(guān)于Python批量下載圖片的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)Python批量下載圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python+OpenCV實(shí)現(xiàn)圖片及視頻中選定區(qū)域顏色識(shí)別
這篇文章主要為大家詳細(xì)介紹了如何利用Python+OpenCV實(shí)現(xiàn)圖片及視頻中選定區(qū)域顏色識(shí)別功能,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-07-07
flask的orm框架SQLAlchemy查詢實(shí)現(xiàn)解析
這篇文章主要介紹了flask的orm框架SQLAlchemy查詢實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
python 字典item與iteritems的區(qū)別詳解
這篇文章主要介紹了python 字典item與iteritems的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
python-序列解包(對(duì)可迭代元素的快速取值方法)
今天小編就為大家分享一篇python-序列解包(對(duì)可迭代元素的快速取值方法),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
Python gevent協(xié)程切換實(shí)現(xiàn)詳解
這篇文章主要介紹了Python gevent協(xié)程切換實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
python編程項(xiàng)目中線上問(wèn)題排查與解決
因?yàn)闃I(yè)務(wù)上的設(shè)計(jì)存在問(wèn)題,導(dǎo)致數(shù)據(jù)庫(kù)表總是被鎖,而且是不定期的鎖定,導(dǎo)致服務(wù)器運(yùn)行異常,今天就來(lái)跟大家說(shuō)說(shuō)該如何避免這種問(wèn)題2021-11-11
人工智能學(xué)習(xí)Pytorch進(jìn)階操作教程
這篇文章主要為大家介紹了人工智能學(xué)習(xí)Pytorch進(jìn)階操作的詳解教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11

