Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I download a file using urllib.request in Python 3?

So, I'm messing around with urllib.request in Python 3 and am wondering how to write the result of getting an internet file to a file on the local machine. I tried this:

g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png')
with open('test.png', 'b+w') as f:
    f.write(g)

But I got this error:

TypeError: 'HTTPResponse' does not support the buffer interface

What am I doing wrong?

NOTE: I have seen this question, but it's related to Python 2's urllib2 which was overhauled in Python 3.

like image 348
Nathan2055 Avatar asked Apr 06 '13 01:04

Nathan2055


2 Answers

change

f.write(g)

to

f.write(g.read())
like image 92
Sheng Avatar answered Oct 07 '22 14:10

Sheng


An easier way I think (also you can do it in two lines) is to use:

import urllib.request
urllib.request.urlretrieve('http://media-mcw.cursecdn.com/3/3f/Beta.png', 'test.png')

As for the method you have used. When you use g = urllib.request.urlopen('http://media-mcw.cursecdn.com/3/3f/Beta.png') you are just fetching the file. You must use g.read(), g.readlines() or g.readline() to read it it.

It's just like reading a normal file (except for the syntax) and can be treated in a very similar way.

like image 32
Xantium Avatar answered Oct 07 '22 15:10

Xantium