python爬蟲抓取圖片
阿新 • • 發佈:2019-02-05
關於python爬蟲一直以來是很著名的,林林總總也有很多方法,大致起來也就是一個原理。
下面我來介紹一下我用的BeautifulSoup獲取的,正則獲取也很簡單,在這裡只說一下BeautifulSoup方法,使用伯樂線上網站作為參考的例子
程式碼如下
#encoding:UTF-8 import urllib2,urllib,random,threading from bs4 import BeautifulSoup import sys reload(sys) sys.setdefaultencoding('utf-8') class Images(threading.Thread): def __init__(self,lock,src): threading.Thread.__init__(self) self.lock=lock self.src=src def run(self): self.lock.acquire() urllib.urlretrieve(self.src,'/home/tron/Python/code/img/'+str(random.choice(range(9999)))) print self.src+"已獲取" self.lock.release() def img_greb(): lock=threading.Lock() site_url = "http://blog.jobbole.com/" html = urllib2.urlopen(site_url).read() soup=BeautifulSoup(html) img=soup.findAll(['img']) for i in img: Images(lock,i.get('src')).start() if __name__ == '__main__': img_greb()
為了提高效率我使用的多執行緒的方法獲取圖片,使用啦urllib中的urlretrieve來下載圖片,其中urlretrieve的引數是這樣的:
urlretrieve(url,filename)
url:圖片的網路路徑
filename:圖片的本地路徑