如何用Python实现MSA认证的SharePoint文件自动下载?
你的问题出在两点:一是用urllib直接访问的是SharePoint的文档预览页面(Doc.aspx),而非文件的直接下载地址;二是没有处理微软账户的OAuth2认证,所以服务器返回的是登录页面内容。
完全可以用Python实现需求,推荐使用专门针对SharePoint的office365-rest-python-client库,它能处理MSA认证和文件操作,步骤如下:
1. 安装依赖库
pip install office365-rest-python-client
2. 编写认证并下载的代码
首先需要获取文件的实际路径(不是预览链接):在SharePoint中找到目标文件,右键→复制→复制链接,选择“直接链接”(MSA账户站点的链接格式一般是https://abc.sharepoint.com/sites/ProductImplementation/Shared%20Documents/Product%20Implementation%20Status-20240531.xlsx这类)。
然后用以下代码:
from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.user_credential import UserCredential # 你的MSA账户信息 username = "your-msa-account@outlook.com" password = "your-msa-password" # SharePoint站点URL和文件路径 site_url = "https://abc.sharepoint.com/sites/ProductImplementation" file_relative_url = "/sites/ProductImplementation/Shared Documents/Product Implementation Status-20240531.xlsx" # 初始化上下文并认证 ctx = ClientContext(site_url).with_credentials(UserCredential(username, password)) # 获取文件对象并下载 file = ctx.web.get_file_by_server_relative_url(file_relative_url) file.download("testngsheet.xlsx").execute_query() print("文件下载完成")
如果你的MSA账户开启了两步验证,需要在微软账户设置里生成应用密码,替换上面的password字段。
其他自动化下载方法
如果不想用Python,还可以用微软官方的Power Automate:
- 新建一个云流,触发条件可设为定时(比如每天固定时间)或文件更新时
- 添加“获取文件内容”动作,选择你的SharePoint站点和目标文件
- 添加“创建文件”动作,将内容保存到本地或指定存储位置
- 配置完成后,流会自动执行认证和下载操作
内容的提问来源于stack exchange,提问作者snehapriya katikala
相关产品推荐
相关产品推荐

