利用python调接口获取物流标签,并转成PDF保存在指定的文件夹。

发布于:2025-03-28 ⋅ 阅读:(19) ⋅ 点赞:(0)

需求

  1. 调用get label 接口
  2. 将接口返回的base64文件转换成pdf
  3. 文件命名用接口返回值的单号命名保存再指定的文件夹重

实现代码

# -*- coding: utf-8 -*-
import requests
import base64
import os
import json  # 新增json模块导入


url = "http://releasud.com/api/label/LableApi/GalProcess"  # 替换为实际API地址
headers = {
    "Content-Type": "application/json",
    "token": "MjAxNjA4MDkxBRDJBOThFNjVCMDBDNTc2OURCM0U3NA=="
}
body = {
    "TrackNumber": "F7532425032000IA",
    "IsNeedLable": True  # 注意字段名与文档一致(原需求可能有拼写错误)
}

try:
    # 发送请求
    response = requests.post(url, json=body, headers=headers)
    response.raise_for_status()  # 检查HTTP状态码
    response_data = response.json()

    # 调试:打印完整响应
    print("完整响应内容:\n", json.dumps(response_data, indent=2, ensure_ascii=False))

    # 检查关键字段结构
    if "Data" not in response_data:
        print("错误:响应中缺少Data字段")
        exit()

    data = response_data["Data"]
    label_encoded = data.get("Label")
    channel_trace_id = data.get("ChannelTraceId")
    msg = data.get("Msg", "无附加信息")

    # 检查Label是否为null
    if label_encoded is None:
        print(f"错误:标签未生成,原因 -> {msg}")
        exit()
    if channel_trace_id is None:
        print("错误:ChannelTraceId为空")
        exit()

    # 解码并保存
    try:
        label_pdf = base64.b64decode(label_encoded)
    except Exception as e:
        print(f"Base64解码失败: {e}")
        exit()

    os.makedirs("Label", exist_ok=True)
    file_path = os.path.join("Label", f"{channel_trace_id}.pdf")

    with open(file_path, "wb") as f:
        f.write(label_pdf)
    print(f"文件保存成功: {file_path}")

except ValueError as e:  # 兼容所有JSON解析错误(新版requests抛JSONDecodeError,旧版抛ValueError)
    print(f"错误:响应不是有效的JSON格式 -> {e}")
    print("原始响应内容:", response.text)
except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")
except KeyError as e:
    print(f"响应字段缺失: {e}")
except Exception as e:
    print(f"未知错误: {e}")

运行结果:

D:\PYTHON-学习\邮政接口压力测试脚本\pythonProject1\.venv\Scripts\python.exe D:\PYTHON-学习\邮政接口压力测试脚本\pythonProject1\huoqu_Label.py 
完整响应内容:
 {
  "Status": 1,
  "Data": {
    "Label": null,
    "Msg": "F7532425032000IA未查询到单号信息!",
    "ChannelTraceId": null,
    "ServiceProviderName": null
  },
  "ErrCode": null,
  "ErrMsg": null
}
错误:标签未生成,原因 -> F7532425032000IA未查询到单号信息!

进程已结束,退出代码为 0