2017-06-27 147 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並添加標題,你不能得到的文件。

希望它能幫助有人在未來爲我工作! 任何改進都超過歡迎! :)