2

我正在使用 PyQt4 和 BeautifulSoup 编写小脚本。基本上你指定 url 而不是脚本应该从网页下载所有图片。

在输出中,当我提供http://yahoo.com时,它会下载除一张以外的所有图片:

...
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"属性,并且您会两次收到相同的错误:一次在file_name = image['src'].split('/')[-1]except 块中,然后在之后'File name is wrong ',image['src']


避免该问题的最简单方法是替换soup.findAll('img')为,soup.findAll('img',{"src":True})这样它只会找到具有src属性的元素。


如果有两种可能性,请尝试以下操作:

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 回答