2017-06-27 144 views
2

我在尝试使用Python脚本从SharePoint存储库下载Excel文件。我使用的示例中定义的Office365-Rest-Python-Client在https://github.com/vgrem/Office365-REST-Python-Client,我可以访问我需要的所有文件/目录。问题出现在我想要下载任何文件的时候。我尝试了几种方法,但它们都不起作用:wget.download("https://shprepos.com/path/file.xlsx", local_path, bar=None)在Python中下载Sharepoint Excel文件

但是我得到一个“403 FORBIDDEN”错误。我也试图与要求:

req = requests.get(ruta, auth=requests.auth.HTTPBasicAuth(username, password), headers=headers) 
with open(local_file, 'wb') as file: 
    file.write(req.content) 

有了这个代码,我发现了网页,而不是Excel文件,我不understan为什么,因为如果我访问的URL“https://shprepos.com/path/file.xlsx”,用正确的身份验证我下载文件。

您是否知道使用wget使用身份验证下载该文件的方式?或者我在requests.get中做错了什么?

我需要获得该文件,并使用在脚本的开头之前的验证我做了一个办法:

ctx_auth = AuthenticationContext(shp_url) 
token = ctx_auth.acquire_token_for_user(username, password) 

你知不知道这样做的方法吗?也许python客户端有一个下载文件的方法,但我找不到它!

非常感谢! :)

Regards

回答

0

是的!我找到了解决方案!我需要获得授权才能下载文件。我在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并添加标题,你不能得到的文件。

希望它能帮助有人在未来为我工作! 任何改进都超过欢迎! :)