Simple instructions on how to programmatically download an image from a web page?

Bengt Richter bokr at oz.net
Thu Nov 27 12:22:41 EST 2003


On 26 Nov 2003 23:00:54 -0800, jarrodhroberson at yahoo.com (Y2KYZFR1) wrote:

>I have search the group and not found a working example on how to
>simply download a .gif from a url.
>
>something as simple as
>http://groups.google.com/images/threadview_logo.gif should be pretty
>easy, guess not?
>
>I don't need to know about using a browser, I need to know how to do
>it programmatically from Python.
>
>Anyone know how to get it done?
I just tried this interactively some example lines from httplib
(the if 1: was just to execute the indented lines in one go)

 >>> import httplib
 >>> if 1:
 ...     conn = httplib.HTTPConnection("www.python.org")
 ...     conn.request("GET", "/pics/PythonPoweredSmall.gif")
 ...     r1 = conn.getresponse()
 ...     print r1.status, r1.reason
 ...     data1 = r1.read()
 ...
 200 OK
 >>> len(data1)
 361
 >>> data1[:8]
 'GIF89a7\x00'
 >>> file('pypowgif.gif','wb').write(data1)
 >>> import os, webbrowser
 >>> webbrowser.open_new(os.path.abspath('pypowgif.gif'))

or using windows file association, also

 >>> os.system(os.path.abspath('pypowgif.gif'))

You should check errors etc., but the data apparently got through
(not the logo you asked for though ;-)


Regards,
Bengt Richter




More information about the Python-list mailing list