开发者

How to download files over HTTP via python-urllib2 correctly?

开发者 https://www.devze.com 2023-03-16 15:53 出处:网络
I\'ve written parser on python to download images from Internet: import urllib2 for i in xrange(1,10): r = urllib2.urlopen(\'http://example.com/\'+str(i)+\'.gif\'))

I've written parser on python to download images from 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()

Images can't be opened. Windows says 'Error while building image'. B开发者_如何学Cut I've found that every line of received file less on 1 byte than this line of original file, but both look similar. How to download correct file?


When working with windows you may need to put the "binary" flag b in open...

f = open(r'C:\\'+str(i)+'.gif','wb')


On Windows you need to specify 'wb', not 'w+'


You can try urllib.urlretrieve - it handles most of details by itself.
So your code will look like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消