2016-04-27 67 views
0

我試圖從URL下載CSV文件&將它保存到我的硬盤上的文件。我試圖在Python 2.7上使用下面的代碼,但得到錯誤。 CSV位於SharePoint網站上。使用Python 2.7從URL下載CSV文件

import urllib 
import csv 

url = 'https://office.com/sites/20Reporting/Lists/Reports/476%20-%2050%20DaySDShrink%20Report/476-%2030%20DaySDShrink.csv' 
csv = urllib.urlopen(url).read() # returns type 'str' 
with open('C:\Users\Documents\DPAM.csv', 'wb') as fx: 
    fx.write(csv) 

我收到以下錯誤消息。

IOError: ('http error', 401, 'Unauthorized', <httplib.HTTPMessage instance at 0x037541E8>) 
+0

你得到的錯誤說明了一切。您無權訪問資源。它依賴於服務器,如果它接受任何授權頭,你將不得不與請求一起發送。 – Terry

+0

嗯,但如果我手動將網址,我可以訪問下載文件。 –

回答

0

嘗試是這樣的:

import urllib2,base64 
import csv 
username ="username" 
password= "password" 
url = 'https://office.com/sites/20Reporting/Lists/Reports/476%20-%2050%20DaySDShrink%20Report/476-%2030%20DaySDShrink.csv' 
request = urllib2.Request(url) 
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') 
request.add_header("Authorization", "Basic %s" % base64string) 
csv = urllib2.urlopen(request).read() 
with open('C:\Users\Documents\DPAM.csv', 'wb') as fx: 
    fx.write(csv) 

你也可以嘗試communicate with sharepoint via SOAP using urllib2