使用Python访问Office 365文件时遇认证及404错误的解决方法
核心原因
传入的url参数不符合SharePoint REST API的路径要求,导致请求/_api/Web时找不到对应资源。
修复步骤
修正URL格式
确保url指向SharePoint站点的根地址,而非文件、文档库或子页面路径。正确示例:url = "https://your-domain.sharepoint.com/sites/YourSiteName"不要包含末尾斜杠或具体文件路径,必须是站点顶层地址。
清理重复认证逻辑
代码中两种认证方式会造成上下文冲突,保留简洁的with_user_credentials方式即可:from office365.sharepoint.client_context import ClientContext url = "https://your-domain.sharepoint.com/sites/YourSiteName" username = "your-account@your-domain.com" password = "your-password" # 简化认证流程 ctx = ClientContext(url).with_user_credentials(username, password) web = ctx.web.get().execute_query() print(f"成功访问站点: {web.url}")验证权限与网络
- 确认账号拥有目标站点的访问权限,手动通过浏览器登录站点验证可访问性。
- 若处于企业内网,需配置代理:
from office365.sharepoint.client_context import ClientContext ctx = ClientContext(url).with_user_credentials(username, password) ctx.set_proxy("http://proxy-server:port", "proxy-username", "proxy-password") web = ctx.web.get().execute_query()
升级依赖版本
旧版office365-REST-Python-Client可能存在API路径匹配问题,执行升级:pip install --upgrade office365-rest-python-client
内容的提问来源于stack exchange,提问作者hoa phan
相关产品推荐
相关产品推荐

