實驗室需要NUS-WIDE數據庫中的原圖,數據集的地址為http://lms.comp.nus.edu.sg/research/NUS-WIDE.htm 由于這個數據只給了每個圖片的URL,所以需要一個小爬蟲程序來爬取這些圖片。在圖片的下載過程中建議使用VPN。由于一些URL已經失效,所以會下載一些無效的圖片。
# PYTHON 2.7 Ubuntu 14.04nuswide = "$NUS-WIDE-urls_ROOT" #the location of your nus-wide-urls.txtimagepath = "$IMAGE_ROOT" # path of dataset you want to download inf = open(nuswide, 'r')url = f.readlines()import reimport urllibimport osreg = r"ImageData.+?jpg"location_re = re.compile(reg)reg = r"(ImageData.+?)/0"direction_re = re.compile(reg)reg = r"http.+?jpg"image_re = re.compile(reg)for i in url: filename = re.findall(location_re, i) direction = re.findall(direction_re, i) image = re.findall(image_re, i) if image: path = imagepath+filename[0] path_n = imagepath+direction[0] print path_n if os.path.exists(path_n): urllib.urlretrieve(image[1], path) else: os.makedirs(path_n) urllib.urlretrieve(image[1], path)
再給大家分享一個爬取百度貼吧圖片的小爬蟲(你懂得)
#coding=utf-8#urllib模塊提供了讀取Web頁面數據的接口import urllib#re模塊主要包含了正則表達式import re#定義一個getHtml()函數def getHtml(url): page = urllib.urlopen(url) #urllib.urlopen()方法用于打開一個URL地址 html = page.read() #read()方法用于讀取URL上的數據 return htmldef getImg(html): reg = r'src="(.+?/.jpg)" pic_ext' #正則表達式,得到圖片地址 imgre = re.compile(reg) #re.compile() 可以把正則表達式編譯成一個正則表達式對象. imglist = re.findall(imgre,html) #re.findall() 方法讀取html 中包含 imgre(正則表達式)的 數據 #把篩選的圖片地址通過for循環遍歷并保存到本地 #核心是urllib.urlretrieve()方法,直接將遠程數據下載到本地,圖片通過x依次遞增命名 x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'D:/E/%s.jpg' % x) x+=1html = getHtml("http://tieba.baidu.com/p/xxxx")print getImg(html)
新聞熱點
疑難解答