python多執行緒圖片爬蟲
阿新 • • 發佈:2019-01-27
學習python後寫的第一個程式:抓妹子圖。。。
環境:linux python2.7
預設放在/home/fantasy/pics/ 目錄下
思路:
1.進入http://girl-atlas.com/後(咳咳,看一下快回來)發現頁面右側每個妹子都有一個標籤,就從這裡下手。
2.針對每個妹子建立一個執行緒,抓取到這個人的名字建立一個資料夾,抓取她的簡介放在這個資料夾裡。
3.接下來就是抓取每個妹子的圖集然後放在剛才建立的資料夾中。
程式碼如下:
結果圖:# -*- coding: utf-8 -*- #!/usr/bin/python #--------------------------------------- # 程式:MM爬蟲 # 版本:0.1 # 作者:fantasy # 日期:2014-06-05 # 語言:Python 2.7 # 功能:將網站的圖片內容分目錄儲存到本地 #---------------------------------------- import string import urllib2 import urllib import re from threading import Thread from Queue import Queue from time import sleep import os import sys #Q是任務佇列(元素針對每個人) #thread_num是併發執行緒總數 Q = Queue() thread_num = 7 #----------- 處理頁面上的各種標籤 ----------- class HTML_Tool: # 用非 貪婪模式 匹配 \t 或者 \n 或者 空格 或者 超連結 或者 圖片 BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)") # 用非 貪婪模式 匹配 任意<>標籤 EndCharToNoneRex = re.compile("<.*?>") # 用非 貪婪模式 匹配 任意<p>標籤 BgnPartRex = re.compile("<p.*?>") CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)") CharToNextTabRex = re.compile("<td>") # 將一些html的符號實體轉變為原始符號 replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," "),(""","\"")] def Replace_Char(self,x): x = self.BgnCharToNoneRex.sub("",x) x = self.BgnPartRex.sub("\n ",x) x = self.CharToNewLineRex.sub("\n",x) x = self.CharToNextTabRex.sub("\t",x) x = self.EndCharToNoneRex.sub("",x) for t in self.replaceTab: x = x.replace(t[0],t[1]) return x #----------- 處理頁面上的各種標籤 ----------- class MM_Spider: # 建構函式 def __init__(self,url): self.myUrl=url self.urlNum=0 self.myTool = HTML_Tool() print u'MM爬蟲start。。。。。。' #header偽裝獲得html內容 def get_html(self,url): req_header = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} req_timeout = 20 try: req = urllib2.Request(url,None,req_header) page = urllib2.urlopen(req,None,req_timeout) html = page.read().decode("utf-8") except urllib2.URLError as e: print e.message except socket.timeout as e: user_html(self.myUrl) return html #每個執行緒去抓一個人的圖,簡介等,要自己組織檔案目錄 def working(self): while True: url=Q.get() self.get_MM_pic(url) #sleep(1) Q.task_done() def get_MM_pic(self,url): personal_page=self.get_html(url) #<title>少女時代 | 美女圖集 —— 美女圖片 美女寫真</title> title=re.search(r'<title>([^ |]*)',personal_page,re.S) print title.group(1) os.mkdir(title.group(1)) #<div class="column grid_12" style="margin-bottom: 10px"> #少女時代(Girls' Generation),是S.M.Entertainment公司在2007年推出的韓國著名女子團體,由金泰妍、鄭秀妍、李順圭、黃美英、金孝淵、權侑莉、崔秀英、林允兒、徐珠賢9名成員組成。於2007年8月5日憑藉《再次重逢的世界》首次舞臺正式出道,於5年內在韓國、中國、日本、泰國等亞洲國家甚至歐美等國家都累積出廣大的知名度。少女時代9名成員都具備不同的個性特點及魅力,她們除了在歌唱事業上表現出眾,在演藝圈其他方面如電視劇、綜藝等也表現出驚人的才華。毫無疑問,她們正在一步步地打造著屬於她們的耀眼舞臺,屬於她們的璀璨時代。 #</div> profile=re.search(r'<div class="column grid_12" style="margin-bottom: 10px">([^<]*)',personal_page,re.S) f = open(title.group(1)+'/'+title.group(1)+'簡介'+'.txt','w+') if profile==None: f.writelines("no profile") else: f.writelines(self.myTool.Replace_Char(profile.group(1))) f.close() #<div class="grid_title"> #<a href='http://girl-atlas.com/a/10140314061500000191' class="caption">[NS Eyes] #184 Sayaka Isoyama 磯山さやか</a> #</div> album=re.findall(r'<a href=\'([^\']*)\' class="caption">',personal_page,re.S) count=0 for item in album: print item #raw_input() count=self.save_MM_page(item,title.group(1),count) def save_MM_page(self,url,catalog,count): photos_page=self.get_html(url) #<img title="2011 Girls Generation『Holiday』1st Part - No. 24 - 24" delay='http://girlatlas.b0.upaiyun.com/45/20121223/0041f70328b00e5535e2.jpg!mid' /> photos=re.findall(r"<img title=.*?delay='(.*?)' />",photos_page,re.S) for item in photos: urllib.urlretrieve(item,catalog+ '/'+'%d.jpg' %count) #print catalog count+=1 return count #主函式 def MM_pic(self): #設定編碼 reload(sys) sys.setdefaultencoding('utf8') #切換目錄 os.chdir('pics') #準備執行緒池 for i in range(thread_num): t=Thread(target=self.working) t.setDaemon(True) t.start() #往佇列中放入任務 myPage=self.get_html(self.myUrl) #<li title='磯山さやか' tid='10' length='13'><a target="_blank" href="http://girl-atlas.com/t/10">磯山さやか</a></li> myItems=re.findall(r'<li title=.*?<a target="_blank" href=\"([^\"]*)\"',myPage,re.S) for item in myItems: Q.put(item) self.urlNum+=1 print item print self.urlNum print u'按任意鍵開始抓取。。。。。。' raw_input() url='http://girl-atlas.com/' mySpider=MM_Spider(url) mySpider.MM_pic() Q.join() print 'enjoy it。。。。。。'
看著這些目錄名字感覺我要被和諧了。。。
參考:
Python爬蟲入門教程:點選開啟連結
感謝pein0119提供網址:點選開啟連結