You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.6.4批量下载图片:按书籍ID建文件夹及URL生成失败求助

Python 3.6.4 批量下载图片并按书籍ID分类的解决方案

Hey there! Let's get this image downloader up and running for you. The issue with your nested loops was probably either messy URL concatenation or missing critical steps like folder creation. Here's a complete, tested solution that fits your exact needs:

Step 1: Install Required Library

First, we'll use requests to handle image downloads—it's way more straightforward than Python's built-in urllib. Since Python 3.6.4 doesn't include it by default, install a compatible version via pip:

pip install requests==2.31.0  # This version works perfectly with Python 3.6.4

Step 2: Full Working Code

# -*- coding: UTF-8 -*-
import os
import requests

# 用模板字符串定义URL结构,避免拼接出错(Python 3.6+支持)
BASE_URL_TEMPLATE = "http://url.com/{book_id}/page-{page_num}.jpg"
# 书籍ID范围:749到826(注意range是左闭右开,所以结束值设为827)
BOOK_ID_RANGE = range(749, 827)
# 每个书籍对应的4张图片页码
PAGE_RANGE = range(1, 5)

def download_single_image(url, save_path):
    """辅助函数:处理单张图片的下载与保存,带基础错误处理"""
    try:
        # 流式下载大文件更稳定
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 主动触发请求失败的异常
        
        with open(save_path, 'wb') as img_file:
            for chunk in response.iter_content(chunk_size=8192):
                img_file.write(chunk)
        print(f"✅ 成功保存: {save_path}")
    except Exception as e:
        print(f"❌ 下载失败 {url}: {str(e)}")

if __name__ == "__main__":
    # 遍历每个书籍ID
    for book_id in BOOK_ID_RANGE:
        # 创建对应书籍ID的文件夹,exist_ok=True避免重复创建报错
        book_folder = f"./book_images/{book_id}"
        os.makedirs(book_folder, exist_ok=True)
        
        # 遍历当前书籍的4张图片
        for page_num in PAGE_RANGE:
            # 生成完整图片URL
            image_url = BASE_URL_TEMPLATE.format(book_id=book_id, page_num=page_num)
            # 定义图片保存路径
            save_path = os.path.join(book_folder, f"page-{page_num}.jpg")
            # 执行下载
            download_single_image(image_url, save_path)

Key Fixes & Explanations

  • Clean URL Construction: Using a string template with format() (or f-strings) eliminates the error-prone string splitting you tried earlier. This ensures every URL is correctly formatted.
  • Automatic Folder Creation: os.makedirs(..., exist_ok=True) handles folder creation for each book ID, so you don't have to manually make directories or worry about duplicate folder errors.
  • Error Resilience: The helper function catches network errors or invalid URLs, so your script won't crash halfway through downloading all images.
  • Correct Range Handling: range(749, 827) covers every book ID from 749 to 826 (Python ranges stop just before the end value), and range(1,5) gives you pages 1 to 4 exactly.

Quick Notes for Python 3.6.4

  • F-strings are fully supported in 3.6, so you can also write URLs like f"http://url.com/{book_id}/page-{page_num}.jpg" for even cleaner code.
  • If you can't install requests, replace the download function with urllib.request.urlretrieve—but requests is far better for handling edge cases like broken links.

内容的提问来源于stack exchange,提问作者Kanglando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:35:28