使用zip文件从URL中提取数据时出现属性错误

时间:2015-06-17 15:22:52

标签: python zip

我正在尝试访问"收益率曲线数据"可在this page上找到。它有一个单选按钮,点击"提交"结果是一个zip文件,我希望从中获取数据。我希望从"检索所有数据"选项。我的代码如下,但是,我在行AttributeError: read中收到错误zipfile = ZipFile(StringIO(request.read())),我不知道如何克服此问题。

import urllib, urllib2
import csv
from StringIO import StringIO
import pandas as pd
import os
from zipfile import ZipFile

my_url = 'http://www.bankofcanada.ca/rates/interest-rates/bond-yield-curves/'
data = urllib.urlencode({'lastchange': 'all'}) 
request = urllib2.Request(my_url, data)
result = urllib2.urlopen(request)

zipfile = ZipFile(StringIO(request.read()))

谢谢

2 个答案:

答案 0 :(得分:2)

在破译链接live copy的html源代码后,以下内容似乎有效 - 至少就我所做的那样:

import urllib, urllib2
import csv
from StringIO import StringIO
import pandas as pd
import os
from zipfile import ZipFile
from pprint import pprint, pformat

my_url = 'http://www.bankofcanada.ca/stats/results/csv'
data = urllib.urlencode({"lookupPage": "lookup_yield_curve.php",
                         "startRange": "1986-01-01",
                         "searchRange": "all"})
request = urllib2.Request(my_url, data)
result = urllib2.urlopen(request)
zipdata = result.read()
zipfile = ZipFile(StringIO(zipdata))
print 'zipfile.namelist(): {}'.format(zipfile.namelist())

输出:

zipfile.namelist(): ['yield_curves.csv']

答案 1 :(得分:0)

根据urllib2文档,urllib2.Request对象没有read函数。您应该尝试 - result.read(),如下所示 -

zipfile = ZipFile(StringIO(result.read()))