我正在使用 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'
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"