分析:因為是要下載所有的圖片,不需要進行篩選。這就簡單多了。圖片一般都在“src=”的後面。
代碼:
# -*- coding:utf-8 -*-__author__ = 'Bohn'import requests, re, osfrom urllib.request import urlretrievedef getHtml(url): #偽裝頭部 user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' headers = {'User-Agent': user_agent} response = requests.get(url) response.encoding = 'utf-8' html = response.text print("Got html") return htmldef getImg(html): #編寫Regex regex = 'src="(.*?)"' pattern = re.compile(regex, re.S) #找到Regex匹配的圖片 imglist = re.findall(pattern, html) print(imglist) x = 1 #判斷這個檔案夾是否存在,不存在就建立 if not(os.path.exists(r'D:\imgsaving')): os.makedirs(r'D:\imgsaving') #下載圖片 for img in imglist: print("正在下載第%s張圖片…" % x) urlretrieve(img, r'D:\imgsaving\%s.jpg' % x) x = x + 1 returntry: #爬取愛課程首頁的圖片 url = r"http://www.icourses.cn/home/" html = getHtml(url) getImg(html) print("OK")except: print('Failed.')