# -*- coding: utf-8 -*- import os import re import urllib URL_REG = re.compile(r'(http://[^/\\]+)', re.I) IMG_REG = re.compile(r'<img[^>]*?src=([\'"])([^\1]*?)\1', re.I) def download(dir, url): global URL_REG, IMG_REG m = URL_REG.match(url) #IMG_REG if not m: print '[Error]Invalid URL: ', url return host = m.group(1) if not os.path.isdir(dir): os.mkdir(dir) #獲取html,提取圖片url html = urllib.urlopen(url).read() imgs = [ item[1].lower() for item in IMG_REG.findall(html) ] f = lambda path: path if path.startswith('http://') else \ host + path if path.startswith('/') else url + '/' + path imgs = list(set(map(f, imgs))) print '[Info]Find %d images.' % len(imgs) #下載圖片 for idx, img in enumerate(imgs): name = img.split('/')[-1] path = os.path.join(dir, name) try: print '[Info]Download(%d): %s' % (idx+1, img) urllib.urlretrieve(img, path) except: print "[Error]Can't download(%d): %s" % (idx+1, img) #運行從這裏開始,第一個參數是保存路徑,第二個參數是網址 savePath = 'E://Imgs' questHTTP = "http://www.qiushibaike.com/" download(savePath, questHTTP)
實際上是想下載淘寶網站上的圖片,惋惜淘寶不讓下!html