我正在尝试使用Python脚本从SharePoint存储库下载Excel文件。我正在使用https://github.com/vgrem/office365-rest-python-client的示例中定义的Office365-rest-python-client,我可以访问我需要的所有文件/目录。当我想下载任何文件时,问题就到了。我已经尝试了几种方法,但是它们都没有用:wget.download("https://shprepos.com/path/file.xlsx", local_path, bar=None)
,但我遇到了" 403禁止"错误。我还尝试了请求:
req = requests.get(ruta, auth=requests.auth.HTTPBasicAuth(username, password), headers=headers)
with open(local_file, 'wb') as file:
file.write(req.content)
使用此代码,我将获取网页,而不是Excel文件,而我不理解为什么,因为如果我访问URL" https://shprepos.com/path/file.xlsx",则正确的身份验证我下载了文件。
您知道使用身份验证使用WGET下载该文件的一种方式吗?还是我在请求中做错了什么?
我需要使用脚本开始时进行的先前身份验证来获取该文件的方法:
ctx_auth = AuthenticationContext(shp_url)
token = ctx_auth.acquire_token_for_user(username, password)
您知道这样做的方法吗?也许Python客户端有一种下载文件的方法,但我找不到它!
非常感谢!:(
问候
是的!我找到了解决方案!!我需要在下载文件之前获得授权。我在Office365-Python-Client的测试文件夹中找到了一个示例。因此,基本上,在使用请求获取URL之前,您获得了授权:
options = RequestOptions(shp_file_path)
ctx_auth.authenticate_request(options)
options.headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f"
options.headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0)"
req = requests.get(shp_file_path, headers=options.headers, verify=True, allow_redirects=True)
if req.ok:
with open(local_file, 'wb') as file:
file.write(req.content)
如果您没有获得auth_request并添加标题,则无法获取文件。
希望将来对我有用的帮助!任何进步都非常欢迎!!:(