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

如何通过Python调用API下载SharePoint列表(非页面文档)的附件

解决方案:Python调用SharePoint API下载列表附件

SharePoint REST API 原生提供了列表附件的专属访问端点,无需使用文档库相关接口,核心端点格式如下:
https://{site url}/sites/{group name}/_api/web/lists/getbytitle('{listname}')/items({item_id})/AttachmentFiles
其中{item_id}为列表每行条目的唯一ID,你可以先拉取全量列表条目获取所有ID,再遍历每个ID拉取对应附件即可。


步骤1:安装依赖库

推荐优先使用微软官方维护的SharePoint Python SDK,避免自行处理认证和协议适配,执行以下命令安装:
pip install requests office365-rest-python-client


步骤2:完整代码实现

方式1:使用官方SDK实现(推荐)

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
import os

# 替换为你自己的配置参数
site_url = "https://{site url}/sites/{group name}"
client_id = "Azure AD注册应用的客户端ID"
client_secret = "Azure AD注册应用的客户端密钥"
list_name = "你的SharePoint列表名称"
local_save_path = "./sharepoint_list_attachments"

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

# 1. 建立SharePoint连接
credential = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(credential)

# 2. 获取目标列表的所有条目
target_list = ctx.web.lists.get_by_title(list_name)
list_items = target_list.items.get().execute_query()

# 3. 遍历条目下载附件
for item in list_items:
    current_item_id = item.properties["Id"]
    # 获取当前条目的所有附件
    attachments = item.attachment_files.get().execute_query()
    if not attachments:
        continue
    # 可按条目ID创建子目录,方便区分不同条目的附件
    item_save_dir = os.path.join(local_save_path, f"item_{current_item_id}")
    os.makedirs(item_save_dir, exist_ok=True)
    for attach_file in attachments:
        save_file_path = os.path.join(item_save_dir, attach_file.properties["FileName"])
        with open(save_file_path, "wb") as f:
            attach_file.download(f).execute_query()
        print(f"附件已下载:{save_file_path}")

方式2:原生requests实现(无需第三方SDK)

import requests
import os

# 替换为你自己的配置参数
site_url = "https://{site url}/sites/{group name}"
access_token = "你的SharePoint访问令牌"
list_name = "你的SharePoint列表名称"
local_save_path = "./sharepoint_list_attachments"

os.makedirs(local_save_path, exist_ok=True)
headers = {
    "Accept": "application/json;odata=verbose",
    "Authorization": f"Bearer {access_token}"
}

# 1. 获取所有列表条目的ID
items_req_url = f"{site_url}/_api/web/lists/getbytitle('{list_name}')/items?$select=Id"
items_resp = requests.get(items_req_url, headers=headers).json()
list_items = items_resp["d"]["results"]

# 2. 遍历条目下载附件
for item in list_items:
    item_id = item["Id"]
    attach_req_url = f"{site_url}/_api/web/lists/getbytitle('{list_name}')/items({item_id})/AttachmentFiles"
    attach_resp = requests.get(attach_req_url, headers=headers).json()
    attachments = attach_resp["d"]["results"]
    if not attachments:
        continue
    item_save_dir = os.path.join(local_save_path, f"item_{item_id}")
    os.makedirs(item_save_dir, exist_ok=True)
    for attach in attachments:
        file_content = requests.get(attach["__metadata"]["media_src"], headers=headers).content
        save_path = os.path.join(item_save_dir, attach["FileName"])
        with open(save_path, "wb") as f:
            f.write(file_content)
        print(f"附件已下载:{save_path}")

注意事项

  • 你需要先在Azure AD中注册应用,为应用分配对应SharePoint站点的列表读写权限,申请管理员同意后才能拿到有效的客户端凭据或访问令牌。
  • 如果是本地部署的SharePoint Server,需要将认证方式替换为NTLM/Kerberos,可搭配requests_ntlm库实现认证。
  • 代码中的list_name需要和SharePoint后台显示的列表实际名称完全一致,不要使用URL中编码后的字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:18:04