如何通过python-urllib2正确下载HTTP文件?

shu*_*ter 5 python image file

我在python上编写了解析器来从Internet下载图像:

import urllib2

for i in xrange(1,10):
  r = urllib2.urlopen('http://example.com/'+str(i)+'.gif'))
  f = open('C:\\' + str(i) + '.gif', 'w+')
  f.write(r.read())
  f.close()
Run Code Online (Sandbox Code Playgroud)

图像无法打开.Windows说"构建图像时出错".但我发现接收文件的每一行都比1行原始文件少,但两者看起来都差不多.如何下载正确的文件?

And*_*ite 13

使用Windows时,您可能需要将"二进制"标志b置于打开状态...

f = open(r'C:\\'+str(i)+'.gif','wb')
Run Code Online (Sandbox Code Playgroud)


小智 5

在Windows上,您需要指定'wb',而不是'w +'


Pil*_*ill 5

您可以尝试urllib.urlretrieve - 它自己处理大部分细节.
所以你的代码看起来像这样:

for i in xrange(1,10):
    urllib.urlretrieve('http://example.com/'+str(i)+'.gif'), 'C:\'+str(i)+'.gif','w+')
Run Code Online (Sandbox Code Playgroud)