Python 爬蟲多線程詳解及執行個體代碼,python爬蟲
python是支援多線程的,主要是通過thread和threading這兩個模組來實現的。thread模組是比較底層的模組,threading模組是對thread做了一些封裝的,可以更加方便的使用。
雖然python的多線程受GIL限制,並不是真正的多線程,但是對於I/O密集型計算還是能明顯提高效率,比如說爬蟲。
下面用一個執行個體來驗證多線程的效率。代碼只涉及頁面擷取,並沒有解析出來。
# -*-coding:utf-8 -*-import urllib2, timeimport threadingclass MyThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) self.args = args self.func = func def run(self): apply(self.func, self.args)def open_url(url): request = urllib2.Request(url) html = urllib2.urlopen(request).read() print len(html) return html
if __name__ == '__main__': # 構造url列表 urlList = [] for p in range(1, 10): urlList.append('http://s.wanfangdata.com.cn/Paper.aspx?q=%E5%8C%BB%E5%AD%A6&p=' + str(p))
# 一般方式 n_start = time.time() for each in urlList: open_url(each) n_end = time.time() print 'the normal way take %s s' % (n_end-n_start)
# 多線程 t_start = time.time() threadList = [MyThread(open_url, (url,)) for url in urlList] for t in threadList: t.setDaemon(True) t.start() for i in threadList: i.join() t_end = time.time() print 'the thread way take %s s' % (t_end-t_start)
分別用兩種方式擷取10個訪問速度比較慢的網頁,一般方式耗時50s,多線程耗時10s。
多線程代碼解讀:
# 建立線程類,繼承Thread類class MyThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) # 調用父類的建構函式 self.args = args self.func = func def run(self): # 線程活動方法 apply(self.func, self.args)
threadList = [MyThread(open_url, (url,)) for url in urlList] # 調用線程類建立新線程,返回線程列表 for t in threadList: t.setDaemon(True) # 設定守護線程,父線程會等待子線程執行完後再退出 t.start() # 線程開啟 for i in threadList: i.join() # 等待線程終止,等子線程執行完後再執行父線程
以上就是本文的全部內容,希望對大家的學習有所協助。