[Tutor] Download an image of a site?
kent37 at tds.net
Tue Sep 13 02:09:25 CEST 2005
Joseph Quigley wrote:
> I'm a Garfield fan and I thought that I'd make a program that would
> enable me to read the online comics without opening firefox and typing
> the url and waiting for all the other junk to load. Here's my code:
> # import modules
> import time
> import urllib2
> class data:
> # Define time and date
> todays_date = time.localtime(time.time())
> dayNum = time.strftime("%d", todays_date)
> monthNum = time.strftime("%m", todays_date)
> yearNum = time.strftime("%y", todays_date)
> yearNumFull = time.strftime("%Y", todays_date)
> # Define url and it's components
> stripName ="http://images.ucomics.com/comics/ga/%s/ga" % (yearNumFull)
> c_strip = "%s%s%s%s.gif" % (stripName, yearNum, monthNum, dayNum)
> f = ""
> # Other info
> c_strip_download = "Downloading Today's Garfield..."
> # Errors
> urllib2_URLError = """Temporary failure in name resolution.
> This means that you may not be online or the site is down.
> You may want to try again later."""
> # Enough defining lets get our hands dirty.
> data.f = urllib2.urlopen(data.c_strip)
> except urllib2.URLError:
> print urllib2_URLError
> data.f.save("%s%s%s.gif" % (data.yearNum, data.monthNum, data.dayNum))
I don't think the object returned from urllib2.urlopen() has save() and get() methods. According to the docs urlopen() "returns a file-like object with two additional methods:
* geturl() -- return the URL of the resource retrieved
* info() -- return the meta-information of the page, as a dictionary-like object"
So you should treat data.f like an open file - use read() to get the contents into a variable. Then open a real (disk) file for writing and write it out. This section of the Python tutorial has a quick intro:
> I would like to know how to save the image to the computer's hard
> drive. Is it something like f.save("%s%s%s.gif" % (yearNum, monthNum,
> dayNum)) ?
> Tutor maillist - Tutor at python.org
More information about the Tutor