使用Python Office365客户端下载SharePoint文件时遇400/404错误
问题现象
使用Office 365 Python客户端通过用户凭证访问SharePoint,可以正常列出文件,但下载操作报错:
- 使用完整文件URL调用
File.open_binary时,返回400错误(无详细响应内容) - 改用站点相对路径写法时,返回404错误,响应提示文件不存在
报错代码示例
示例1:完整URL写法(报400)
from office365.runtime.auth.authentication_context import AuthenticationContext,UserCredential from office365.sharepoint.client_context import ClientContext from office365.sharepoint.files.file import File import logging url = "https://xxxxxx.sharepoint.com/" username= "xxxxxx@xxxxxx.org" password= "xxxxxxxx" ctx = ClientContext(url).with_user_credentials(username, password) file_url = "https://xxxxxxx.sharepoint.com/sites/xxxxxxx/Shared Documents/Public/xxxxxx.pdf" response = File.open_binary(ctx, file_url) print(response) with open("./xxxxxx.pdf", "wb") as local_file: local_file.write(response.content)
示例2:相对路径写法(报404)
context = ClientContext(url).with_user_credentials(username, password) response = File.open_binary(context, '/'.join(['/sites/xxxxx/Shared Documents/Public', 'xxxxx.pdf'])) print(response)
404错误响应内容
b'{"error":{"code":"-2130575338, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The file /sites/xxxx/Shared Documents/Public/xxxxxx.pdf does not exist."}}}'
解决方法
1. 修正ClientContext的站点指向
当前代码中ClientContext初始化用的是SharePoint根站点URL,但目标文件位于子站点/sites/xxxxxxx/下,必须将上下文指向子站点:
site_url = "https://xxxxxx.sharepoint.com/sites/xxxxxxx/" ctx = ClientContext(site_url).with_user_credentials(username, password)
2. 使用正确的相对路径
当上下文指向子站点后,文件路径需使用相对于该子站点的路径,无需包含/sites/xxxxxxx/前缀:
file_relative_path = "Shared Documents/Public/xxxxxx.pdf" response = File.open_binary(ctx, file_relative_path)
3. 前置验证文件状态(可选)
可以先通过API验证文件是否存在、权限是否正常,避免直接下载时报错:
try: file = ctx.web.get_file_by_server_relative_url(file_relative_path).get().execute_query() print(f"文件存在:{file.name}") except Exception as e: print(f"验证失败:{e}")
完整可运行代码
from office365.sharepoint.client_context import ClientContext from office365.sharepoint.files.file import File from office365.runtime.auth.user_credential import UserCredential # 子站点完整URL site_url = "https://xxxxxx.sharepoint.com/sites/xxxxxxx/" username = "xxxxxx@xxxxxx.org" password = "xxxxxxxx" # 初始化上下文 ctx = ClientContext(site_url).with_credentials(UserCredential(username, password)) # 文件相对于子站点的路径 file_relative_path = "Shared Documents/Public/xxxxxx.pdf" # 验证文件存在性 try: file = ctx.web.get_file_by_server_relative_url(file_relative_path).get().execute_query() except Exception as e: print(f"文件不存在或权限不足:{str(e)}") exit() # 下载文件 response = File.open_binary(ctx, file_relative_path) with open("./xxxxxx.pdf", "wb") as local_file: local_file.write(response.content) print("文件下载成功")
内容的提问来源于stack exchange,提问作者Axen_Rangs
相关产品推荐
相关产品推荐

