题
我困惑,为什么我无法从的FriendFeed 下载的一些JSON响应的全部内容使用的urllib2 。
>>> import urllib2
>>> stream = urllib2.urlopen('http://friendfeed.com/api/room/the-life-scientists/profile?format=json')
>>> stream.headers['content-length']
'168928'
>>> data = stream.read()
>>> len(data)
61058
>>> # We can see here that I did not retrieve the full JSON
... # given that the stream doesn't end with a closing }
...
>>> data[-40:]
'ce2-003048343a40","name":"Vincent Racani'
我如何可以检索的urllib2充分反应?
解决方案
最佳的方式来获得的所有数据:
fp = urllib2.urlopen("http://www.example.com/index.cfm")
response = ""
while 1:
data = fp.read()
if not data: # This might need to be if data == "": -- can't remember
break
response += data
print response
原因在于,.read()
不保证返回整个响应,给出插座的性质。我认为这是文档(也许urllib
)中所讨论的,但我不能找到它。
其他提示
使用 tcpdump的(或类似的东西)监测实际的网络交互 - 那么你可以分析一下为什么网站打破了一些客户端库。确保您通过脚本测试重复多次,所以你可以看到,如果这个问题是一致的:
import urllib2
url = 'http://friendfeed.com/api/room/friendfeed-feedback/profile?format=json'
stream = urllib2.urlopen(url)
expected = int(stream.headers['content-length'])
data = stream.read()
datalen = len(data)
print expected, datalen, expected == datalen
该网站的工作始终如一地为我,所以我不能给寻找失败的例子:)
请致电stream.read(),直到它完成...
while data = stream.read() :
... do stuff with data
readlines()
也适用
不隶属于 StackOverflow