Webページから画像をダウンロードするpythonスクリプトを作成しようとしています.Webページ(NASAの今日の写真ページを使用しています)では、新しい写真が毎日投稿され、ファイル名が異なります。
したがって、私の解決策は、HTMLParser を使用して HTML を解析し、「jpg」を探し、画像のパスとファイル名を HTML パーサー オブジェクトの属性 (「出力」という名前、以下のコードを参照) に書き込むことでした。
私はPythonとOOPを初めて使用するので(これは私の最初の実際のPythonスクリプトです)、これが一般的にどのように行われるかはわかりません。アドバイスやポインタは大歓迎です。
ここに私のコードがあります:
# 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 #return the path+file name of the image
parser = MyHTMLParser()
parser.feed(html)
imgurl='http://apod.nasa.gov/apod/'+parser.output