使用Python实现调用API获取图片存储到本地的方法

2025-05-23 15:50

本文主要是介绍使用Python实现调用API获取图片存储到本地的方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接...

使用Python实现调用API获取图片存储到本地

使用Python实现调用API获取图片存储到本地的方法

1、项目概述

开发一个自动化工具,用于从jsON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接调用API获取的文件完全一致。

2、核心功能

自动编程解析含嵌套结构的JSON输入文件

API请求模拟引擎

精确复现Postman请求行为

支持自动重定向跟踪

禁用自动解压缩(保留原始二进制流)

3、环境准备

# 安装依赖
pip install requests python-magic-bin==0.4.24  # Windows
pip install requests python-magic           # linux/MACOS

编辑input.json文件格式:

[
  {
    "postimage": "{...}",
    "preimage": "{...}",
    "original_image_id": "6cd6187a-a20e-f011-998a-000d3www.chinasem.cnac8927d"
  },
  // 更多数据条目...
]

4、代码实现

import json
import requests
import base64
import os
import mimetypes
# 配置参数
INPUT_JSON = "input.json"  # 输入的JSON文件路径
OUTPUT_DIR = "raw_images"   # 图片输出目录(修改目录以示区别)
API_URL = "https://prod-53.southeastasia.logic.azure.com:443/workflows/8de920a489c7490a9e2207bd538ce964/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=qO01WQl5tzdzeGpeVid43SpndovXbq4G7QO0NWcz7B8"
def determine_image_type(base64_str):
    """通过数据URI或魔术数字检测图片类型"""
    try:
        # 处理数据URI格式
        if base64_str.startswith("data:image/"):
            mime_type = base64_str.split(";")[0].split(":")[1]
            return mimetypes.guess_extension(mime_type) or ".png"
        # 通过魔术数字检测原始二进制格式
        decoded = base64.b64decode(base64_str)
        if decoded.startswith(b'\xff\xd8\xff'):
            return ".jpg"
        elif decoded.startswith(b'\x89PNG\r\n\x1a\n'):
            return ".png"
        elif decoded.startswith(b'GIF87a') or decoded.starChina编程tswith(b'GIF89a'):
            return ".gif"
        elif decoded.startswith(b'RIFF') and decoded[8:12] == b'WEBP':
            return ".webp"
    except Exception:
        pass
    return ".bin"  # 未知类型
def process_images():
    # 创建输出目录
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    # 读取JSON文件
    try:
      jEAPwo  with open(INPUT_JSON, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        print(f"读取JSON文件失败: {e}")
        return
    # 遍历处理每个条目
    for id编程China编程x, item in enumerate(data, 1):
        image_id = item.get("original_image_id")
        if not image_id:
            print(f"条目 {idx} 缺少original_image_id,已跳过")
            continue
        print(f"正在处理 ({idx}/{len(data)}): {image_id}")
        # 调用API
        try:
            response = requests.post(
                API_URL,
                json={"EntityGuid": image_id},
                headers={"Content-Type": "application/json"},
                timeout=60  # 延长超时时间
            )
            print(f"响应状态码: {response.status_code}")
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"API调用失败: {str(e)[:200]}")  # 显示部分错误信息
            continue
        # 处理base64数据
        try:
            base64_str = response.text
            # 检测并分割数据URI
            if "," in base64_str:
                header, payload = base64_str.split(",", 1)
                file_ext = determine_image_type(header)
                base64_str = payload
            else:
                decoded = base64.b64decode(base64_str)
                file_ext = determine_image_type(base64_str)
            # 解码base64
            image_data = base64.b64decode(base64_str)
            # 生成文件名(保留原始格式)
            output_path = os.path.join(OUTPUT_DIR, f"{image_id}{file_ext}")
            # 保存原始二进制数据
            with open(output_path, "wb") as f:
                f.write(image_data)
            print(f"原始图片已保存至: {output_path} ({len(image_data):,} bytes)")
        except Exception as e:
            print(f"处理失败: {str(e)[:200]}")
if __name__ == "__main__":
    process_images()

5、结果查看

使用Python实现调用API获取图片存储到本地的方法

补充:python 图片抓取 并保存到本地

import requests
from bs4 import BeautifulSoup
from PIL import Image
import os 
from io import BytesIO
import time
url = "http://www.yestone.com/gallery/1501754333627"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
items = soup.find('div',class_='images-list')
folder_path = './photo'
# html = requests.get('http://st2.cdn.yestone.com/thumbs/2704315/vector/11688/116887226/api_thumb_450.jpg')
# html = requests.get('/_nuxt/img/4c1a746.jpg')
# print(html.content)
# image = Image.open(BytesIO(html.content))
# image.save(folder_path+"/aaa.jpg")
# print(items.find_all('img'))
# exit()
if os.path.exists(folder_path) == False:
   os.makedirs(folder_path)
for index, item in enumerate(items.find_all('img')):
    if item:
        html = requests.get(item.get('src'))
        img_name = str(index + 1) + '.jpg'
        image = Image.open(BytesIO(html.content))
        image.save(folder_path+"/"+img_name)
        print('第%d张图片下载完成' % (index + 1))
        time.sleep(1)  # 自定义延时
print('抓取完成')

到此这篇关于使用Python实现调用API获取图片存储到本地的文章就介绍到这了,更多相关python 获取图片存储到本地内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于使用Python实现调用API获取图片存储到本地的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154748

相关文章

golang中slice扩容的具体实现

《golang中slice扩容的具体实现》Go语言中的切片扩容机制是Go运行时的一个关键部分,它确保切片在动态增加元素时能够高效地管理内存,本文主要介绍了golang中slice扩容的具体实现,感兴趣... 目录1. 切片扩容的触发append 函数的实现2. runtime.growslice 函数gro

python进行while遍历的常见错误解析

《python进行while遍历的常见错误解析》在Python中选择合适的遍历方式需要综合考虑可读性、性能和具体需求,本文就来和大家讲解一下python中while遍历常见错误以及所有遍历方法的优缺点... 目录一、超出数组范围问题分析错误复现解决方法关键区别二、continue使用问题分析正确写法关键点三

golang实现动态路由的项目实践

《golang实现动态路由的项目实践》本文主要介绍了golang实现动态路由项目实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习... 目录一、动态路由1.结构体(数据库的定义)2.预加载preload3.添加关联的方法一、动态路由1

Golang interface{}的具体使用

《Golanginterface{}的具体使用》interface{}是Go中可以表示任意类型的空接口,本文主要介绍了Golanginterface{}的具体使用,具有一定的参考价值,感兴趣的可以了... 目录一、什么是 interface{}?定义形China编程式:二、interface{} 有什么特别的?✅

MySQL数据库实现批量表分区完整示例

《MySQL数据库实现批量表分区完整示例》通俗地讲表分区是将一大表,根据条件分割成若干个小表,:本文主要介绍MySQL数据库实现批量表分区的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录一、表分区条件二、常规表和分区表的区别三、表分区的创建四、将既有表转换分区表脚本五、批量转换表为分区

windows和Linux安装Jmeter与简单使用方式

《windows和Linux安装Jmeter与简单使用方式》:本文主要介绍windows和Linux安装Jmeter与简单使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows和linux安装Jmeter与简单使用一、下载安装包二、JDK安装1.windows设

Spring 缓存在项目中的使用详解

《Spring缓存在项目中的使用详解》Spring缓存机制,Cache接口为缓存的组件规范定义,包扩缓存的各种操作(添加缓存、删除缓存、修改缓存等),本文给大家介绍Spring缓存在项目中的使用... 目录1.Spring 缓存机制介绍2.Spring 缓存用到的概念Ⅰ.两个接口Ⅱ.三个注解(方法层次)Ⅲ.

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

Spring Boot 整合 Redis 实现数据缓存案例详解

《SpringBoot整合Redis实现数据缓存案例详解》Springboot缓存,默认使用的是ConcurrentMap的方式来实现的,然而我们在项目中并不会这么使用,本文介绍SpringB... 目录1.添加 Maven 依赖2.配置Redis属性3.创建 redisCacheManager4.使用Sp

PyTorch中cdist和sum函数使用示例详解

《PyTorch中cdist和sum函数使用示例详解》torch.cdist是PyTorch中用于计算**两个张量之间的成对距离(pairwisedistance)**的函数,常用于点云处理、图神经网... 目录基本语法输出示例1. 简单的 2D 欧几里得距离2. 批量形式(3D Tensor)3. 使用不