497 字
2 分钟
批量下载并去重随机图片脚本
2025-08-04

前言#

前端时间在网上整了个虚拟主机,闲着无聊就打算整个随机图站

本来想找别人要图包的,但别人懒得打包让我自己爬他的api

然后让 DeepSeek 写了个python脚本


准备#

安装依赖:pip install requests


脚本#

创建一个py文件然后把脚本复制进去

修改相关参数后,运行脚本后将自动创建目录并下载图片

支持所有图片格式(webp/jpg/png等),自动保留原始格式

import requests
import os
import time
import random
from urllib.parse import urlparse

def get_image_url():
    """获取重定向后的真实图片URL"""
    try:
        response = requests.head(
            "https://tyy.ayyy.cc/pc",
            allow_redirects=True,
            timeout=5,
            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"
            }
        )
        return response.url if response.status_code == 200 else None
    except Exception:
        return None

def download_image(url, save_dir):
    """下载并保存图片,返回保存的文件名"""
    try:
        # 从URL提取文件名
        filename = os.path.basename(urlparse(url).path)
        save_path = os.path.join(save_dir, filename)

        # 如果文件已存在则跳过
        if os.path.exists(save_path):
            return None

        # 下载图片
        response = requests.get(url, stream=True, timeout=10)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)
            return filename
    except Exception:
        pass
    return None

def main():
    # 配置参数
    SAVE_DIR = "downloaded_images"  # 图片保存目录
    TARGET_COUNT = 1000              # 目标下载数量
    MAX_ATTEMPTS = 500              # 最大尝试次数
    RETRY_DELAY = 0.5               # 重试延迟(秒)

    # 创建保存目录
    os.makedirs(SAVE_DIR, exist_ok=True)

    print(f"开始批量下载图片,目标数量: {TARGET_COUNT}")
    downloaded_count = 0
    attempt_count = 0

    while downloaded_count < TARGET_COUNT and attempt_count < MAX_ATTEMPTS:
        attempt_count += 1

        # 获取图片URL
        image_url = get_image_url()
        if not image_url:
            time.sleep(RETRY_DELAY)
            continue

        # 下载图片
        result = download_image(image_url, SAVE_DIR)
        if result:
            downloaded_count += 1
            print(f"[{downloaded_count}/{TARGET_COUNT}] 下载成功: {result}")

        # 随机延迟防止请求过快
        time.sleep(RETRY_DELAY + random.uniform(0, 0.3))

    print("\n下载完成!")
    print(f"总尝试次数: {attempt_count}")
    print(f"成功下载数量: {downloaded_count}")
    print(f"图片保存目录: {os.path.abspath(SAVE_DIR)}")

    print("处理完成,等待 60 秒后退出...")
    time.sleep(60)  # 等待 60 秒

if __name__ == "__main__":
    main()

使用延申#

修改API地址,替换第11行链接: https://tyy.ayyy.cc/pc

修改下载数量: TARGET_COUNT = 1000

修改保存目录: SAVE_DIR = "downloaded_images"

批量下载并去重随机图片脚本
作者
水沐风
发布于
2025-08-04
许可协议
CC BY-NC-SA 4.0