# -*- coding:utf-8 -*- ''' 使用urllib和BeautifulSoup 简单的实现从百度贴吧获取图片''' from urllib.request import Request,urlopen,urlretrieve import traceback from bs4 import BeautifulSoup # urlopen请求HTML html=urlopen("http://tieba.baidu.com/f?kw=%E9%A3%8E%E6%99%AF&ie=utf-8&pn=0") # BeautifulSoup解析网站 bsObj = BeautifulSoup(html,'html.parser') x=0 imagelist = bsObj.find_all("img") for image in imagelist: try: # print("url:",image['src']) if image['src']: print("url:", image['src']) # urlretrieve远程下载并且保存在本地 urlretrieve(image['src'],'F:pic\%s.jpg'%x) x+=1 except Exception as e: print("e :",e) fs = traceback.format_exc() print("fs:",fs)