我正在使用 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"
最佳答案
这意味着 image
元素没有 "src"
属性,你会得到两次相同的错误:一次在 file_name = image[ 'src'].split('/')[-1]
然后在 except block 中 '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
关于python - 美汤这个错误是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14587728/