Problem with downloading from www

Fredrik Lundh fredrik at pythonware.com
Tue Apr 12 02:36:07 EDT 2005


"NewFilmFan" <gg at yahoo.com> wrote:

> I wrote this program:
>
> import httplib
> conn = httplib.HTTPConnection("www.x.net")
> conn.request("GET", "/x/y.jpg")
> r1 = conn.getresponse()
> print r1.status, r1.reason
> data = r1.read()
> datei = open('test.jpg','w')
> datei.write(data)
> datei.close()

if all you want to do is to download files from the web, urllib is a lot more
convenient:

    urllib.urlretrieve("http://www.x.net/x.y.jpg", "test.jpg")

> It is almost a copy of the manual. Now I can establish the connection and
> receive the data. (The first response from the server is 200, OK.) The jpg
> file is 198 K. But it is not a valid jpeg file. When I download with my
> browser, the file has the length 197K and it is valid, of course. Is this
> a problem of writing text or binary data to a file?

changing the open() call to

    datei = open('test.jpg','wb')

should fix this.

see the library documentation for details.

</F> 






More information about the Python-list mailing list