beautiful soup中的这个错误是什么意思?
我正在用PyQt4和BeautifulSoup写一个小脚本。基本上,你只需要指定一个网址,然后这个脚本就会从网页上下载所有的图片。
在输出结果中,当我提供 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"
2 个回答
2
好的,事情是这样的。在你的try-except代码块中,你遇到了一个KeyError
错误,这个错误是因为在file_name = image['src'].split('/')[-1]
这行代码中,image
这个对象没有src
这个属性。
然后,在你的except
语句之后,你又试图访问同样导致错误的属性:print 'File name is wrong ',image['src']
。
检查一下导致错误的img
标签,并重新考虑一下在这些情况下你的逻辑是否合理。
7
这段话的意思是,image
这个元素没有"src"
属性,所以你会遇到同样的错误两次:第一次是在file_name = image['src'].split('/')[-1]
这行代码里,第二次是在异常处理的部分'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