要以编程方式从SharePoint站点下载文件,您可以使用SharePoint的REST API或Microsoft Graph API。以下是一个使用Python和SharePoint REST API的示例:
requests
库,如果您还没有安装,请使用以下命令安装:pip install requests
https://example.sharepoint.com/sites/mySite/Shared%20Documents/myFile.docx
,则URL为https://example.sharepoint.com/sites/mySite
,文件的相对路径为/Shared Documents/myFile.docx
。import requests
def download_file_from_sharepoint(url, relative_path, username, password):
# 构建请求URL
api_url = f"{url}/_api/web/GetFileByServerRelativeUrl('{relative_path}')/$value"
# 发送请求
response = requests.get(api_url, auth=(username, password))
# 检查响应状态
if response.status_code == 200:
# 保存文件
with open("myFile.docx", "wb") as f:
f.write(response.content)
else:
print(f"Error: {response.status_code}")
# 使用示例
url = "https://example.sharepoint.com/sites/mySite"
relative_path = "/Shared Documents/myFile.docx"
username = "your_username"
password = "your_password"
download_file_from_sharepoint(url, relative_path, username, password)
请注意,此示例仅适用于基本身份验证。对于更高级的身份验证方法,您可以使用ADAL库。
如果您想使用Microsoft Graph API,请参阅Microsoft Graph文档以获取更多信息。
领取专属 10元无门槛券
手把手带您无忧上云