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

如何用Python Office365库访问仅知共享链接的SharePoint文件

通过Python Office365库访问仅提供共享链接的SharePoint文件

针对你只有单个文件共享链接、无对应文件夹权限的场景,常规路径遍历API必然会触发权限错误,必须用Office365库中支持共享链接的专用方法直接定位文件,以下是具体实现方案:

核心思路

利用Office365库的get_share_by_link方法,通过共享链接中的访问令牌直接获取文件对象,无需遍历文件夹,该方法可以绕过文件夹权限验证,直接访问目标文件。

前置准备

先确保安装/升级到最新版的Office365 Python库:

pip install --upgrade office365-rest-python-client

代码实现

from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.credentials import UsernamePasswordCredential

# 配置参数
username = "你的账号邮箱"
password = "你的账号密码"
# 站点基础URL:从共享链接提取,比如共享链接是https://xxx.sharepoint.com/:x:/s/xxx/...,则站点URL为https://xxx.sharepoint.com/sites/xxx
site_url = "https://[redacted].sharepoint.com/sites/[redacted]"
shared_file_link = "https://[redacted].sharepoint.com/:x:/s/[redacted]/dir1/dir2/ESd0HkNNSbJMhQFavQsr9-4BNHC2rHSWsnbs3zRdjtZsC3g"

# 初始化认证与上下文
cred = UsernamePasswordCredential(username, password)
ctx = ClientContext(site_url).with_credentials(cred)

# 通过共享链接获取文件对象
shared_item = ctx.web.get_share_by_link(shared_file_link).execute_query()
file_item = shared_item.listItemAllFields.execute_query()

# 获取元数据(示例:文件名、最后修改日期)
file_name = shared_item.properties.get("Name")
last_modified_date = file_item.properties.get("Modified")
print(f"文件名: {file_name}")
print(f"最后修改日期: {last_modified_date}")

# 获取文件内容并保存到本地
file_content = shared_item.open_binary().execute_query()
with open(file_name, "wb") as f:
    f.write(file_content)

关键注意事项

  • 站点URL正确性:必须是共享链接对应的SharePoint站点基础URL,不能直接使用共享链接。如果不确定站点URL,可以打开共享链接,右键点击页面顶部的站点名称复制链接,提取基础部分。
  • 权限验证:确保你的账号确实被该共享链接授权访问(你提到验证环节正常,这一步无需额外排查)。
  • 链接兼容性:代码对编辑权限(:x:)和查看权限(:v:)的共享链接均适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:10:31