當需要一次保存大量網路圖片時,手動下載往往既費時又容易遺漏。本文以 Python 為例,說明如何解析 JSON 資料、批次下載圖片,並自動建立可離線瀏覽的 HTML 頁面。
目標頁面通常會透過 AJAX 取得資料,回傳的 JSON 中會包含多個字典物件。實作時可重點觀察兩個欄位:一個是圖片說明,另一個是圖片網址。只要取得這兩個資訊,就能開始撰寫下載腳本。
以下範例使用 Python 3,僅需標準函式庫即可完成基本流程。
import json
import os
import urllib.request
from datetime import datetime
def get_json(page, category):
url = "https://example.com/index.php/request/new_data2/{}/{}".format(page, category)
with urllib.request.urlopen(url) as response:
return json.loads(response.read().decode("utf-8"))
從 JSON 中取出圖片網址與說明文字,將圖片寫入以時間命名的資料夾,同時保留對應文字,方便後續生成頁面。
def download(items, folder):
os.makedirs(folder, exist_ok=True)
files = []
for i, item in enumerate(items):
img_url = item["i"]
text = item["t"]
with urllib.request.urlopen(img_url) as res:
content_type = res.headers.get("content-type", "")
ext = ".jpg" if "jpeg" in content_type else ".gif"
filename = "{}{}".format(i, ext)
filepath = os.path.join(folder, filename)
with open(filepath, "wb") as f:
f.write(res.read())
files.append((filename, text))
return files
將下載完成的圖片與說明文字組合成一個簡單頁面,即可用瀏覽器開啟。
def create_html(files, folder):
html = ['<html><meta charset="utf-8"><title>圖片集</title><body>']
for filename, text in files:
html.append('<div><img src="{}/{}"/><p>{}</p></div>'.format(folder, filename, text))
html.append('</body></html>')
with open("{}.html".format(folder), "w", encoding="utf-8") as f:
f.write("\n".join(html))
最後只要指定分類與頁數,就能批次抓取、下載並輸出頁面。
def main(category, pages):
folder = "{}_{}".format(category, datetime.now().strftime("%m%d%H%M%S"))
all_items = []
for page in range(pages):
all_items.extend(get_json(page, category))
files = download(all_items, folder)
create_html(files, folder)
main("tws", 2)
這個做法不需要額外框架,適合作為小型備份或離線閱讀用途。若資料量較大,可再加入非同步請求、錯誤重試與更完整的檔案命名規則,讓流程更穩定。