3

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
4

1 に答える 1

3

文字列がで終わるかどうかを確認するには、スライスの代わりに"jpg"使用できます。.endswith()len()

if name == "href" and value.endswith("jpg"):
   self.output = value

Web ページ内の検索がより複雑な場合は、次の例の代わりにlxml.htmlorを使用できます。BeautifulSoupHTMLParser

from lxml import html

# download & parse web page
doc = html.parse('http://apod.nasa.gov/apod/astropix.html').getroot()

# find <a href that ends with ".jpg" and 
# that has <img child that has src attribute that also ends with ".jpg"
for elem, attribute, link, _ in doc.iterlinks():
    if (attribute == 'href' and elem.tag == 'a' and link.endswith('.jpg') and
        len(elem) > 0 and elem[0].tag == 'img' and
        elem[0].get('src', '').endswith('.jpg')):
        print(link)
于 2013-03-12T00:32:41.143 に答える