使用Python 2.7从URL下载CSV文件

时间:2016-04-27 11:05:48

标签: python-2.7 csv url

我尝试从网址&amp ;;下载CSV文件将其保存到我的硬盘上的文件中。我试图在Python 2.7上使用以下代码但是会出错。 CSV位于SharePoint网站上。

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>)

1 个答案:

答案 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