patternpythonMinor
Download an image from a webpage
Viewed 0 times
downloadfromimagewebpage
Problem
I am trying to write a Python script that download an image from a webpage. On the webpage (I am using NASA's picture of the day page), a new picture is posted everyday, with different file names. After download, set the image as desktop.
My solutions was to parse the HTML using
The code works, but I am just looking for comments and advice. I am new to Python and OOP (this is my first real python script ever), so I am not sure if this is how it is generally done.
My solutions was to parse the HTML using
HTMLParser, looking for "jpg", and write the path and file name of the image to an attribute (named as "output", see code below) of the HTML parser object.The code works, but I am just looking for comments and advice. I am new to Python and OOP (this is my first real python script ever), so I am not sure if this is how it is generally done.
import urllib2
import ctypes
from HTMLParser import HTMLParser
# Grab image url
response = urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html')
html = response.read()
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, print it.
if name == "href":
if value[len(value)-3:len(value)]=="jpg":
#print value
self.output=value
parser = MyHTMLParser()
parser.feed(html)
imgurl='http://apod.nasa.gov/apod/'+parser.output
print imgurl
# Save the file
img = urllib2.urlopen(imgurl)
localFile = open('desktop.jpg', 'wb')
localFile.write(img.read())
localFile.close()
# set to desktop(windows method)
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "desktop.jpg" , 0)Solution
# Save the file
img = urllib2.urlopen(imgurl)
localFile = open('desktop.jpg', 'wb')
localFile.write(img.read())
localFile.close()For opening file it's recommend to do:
with open('desktop.jpg','wb') as localFile:
localFile.write(img.read())Which will make sure the file closes regardless.
Also, urllib.urlretrieve does this for you.
Code Snippets
# Save the file
img = urllib2.urlopen(imgurl)
localFile = open('desktop.jpg', 'wb')
localFile.write(img.read())
localFile.close()with open('desktop.jpg','wb') as localFile:
localFile.write(img.read())Context
StackExchange Code Review Q#23759, answer score: 2
Revisions (0)
No revisions yet.