2

PyQt4とBeautifulSoupを使用して小さなスクリプトを実行しています。基本的に、Webページからすべての写真をダウンロードすることになっているスクリプトよりもURLを指定します。

出力では、 http: //yahoo.comを提供すると、1つを除くすべての画像がダウンロードされます。

...
Download Complete
Download Complete
File name is wrong 
Traceback (most recent call last):
  File "./picture_downloader.py", line 41, in loadComplete
    self.download_image()
  File "./picture_downloader.py", line 58, in download_image
    print 'File name is wrong ',image['src']
  File "/usr/local/lib/python2.7/dist-packages/beautifulsoup4-4.1.3-py2.7.egg/bs4/element.py", line 879, in __getitem__
    return self.attrs[key]
KeyError: 'src'

http://stackoverflow.comからの出力は次のとおりです。

Download Complete
File name is wrong  h
Download Complete

そして最後に、ここにコードの一部があります:

# SLOT for loadFinished
def loadComplete(self): 
    self.download_image()

def download_image(self):
    html = unicode(self.frame.toHtml()).encode('utf-8')
    soup = bs(html)

    for image in soup.findAll('img'):
        try:
            file_name = image['src'].split('/')[-1]
            cur_path = os.path.abspath(os.curdir)
            if not os.path.exists(os.path.join(cur_path, 'images/')):
                os.makedirs(os.path.join(cur_path, 'images/'))
            f_path = os.path.join(cur_path, 'images/%s' % file_name)
            urlretrieve(image['src'], f_path)
            print "Download Complete"
        except:
            print 'File name is wrong ',image['src']
    print "No more pictures on the page"
4

2 に答える 2

6

これは、image要素に"src"属性がなく、同じエラーが 2 回発生することを意味しfile_name = image['src'].split('/')[-1]ます'File name is wrong ',image['src']


この問題を回避する最も簡単な方法は、属性を持つ要素のみを検索するようsoup.findAll('img')に置き換えることです。soup.findAll('img',{"src":True})src


2 つの可能性がある場合は、次のようにしてみてください。

for image in soup.findAll('img'):
    v = image.get('src', image.get('dfr-src'))  # get's "src", else "dfr_src"
                                                # if both are missing - None
    if v is None:
        continue  # continue loop with the next image
    # do your stuff
于 2013-01-29T16:42:40.583 に答える
2

さて、これが起こっていることです。そのオブジェクトには属性がないため、try-except 内でKeyErrorfrom を取得しています。file_name = image['src'].split('/')[-1]src

次に、exceptステートメントの後、エラーの原因となったのと同じ属性にアクセスしようとしています: print 'File name is wrong ',image['src'].

imgエラーの原因となっているタグを調べて、それらのケースのロジックを再評価してください。

于 2013-01-29T16:47:37.687 に答える