Python3多線程爬蟲實例講解代碼
多線程概述
多線程使得程序內(nèi)部可以分出多個線程來做多件事情,充分利用CPU空閑時間,提升處理效率。python提供了兩個模塊來實現(xiàn)多線程thread 和threading ,thread 有一些缺點,在threading 得到了彌補。并且在Python3中廢棄了thread模塊,保留了更強大的threading模塊。
使用場景
在python的原始解釋器CPython中存在著GIL(Global Interpreter Lock,全局解釋器鎖),因此在解釋執(zhí)行python代碼時,會產(chǎn)生互斥鎖來限制線程對共享資源的訪問,直到解釋器遇到I/O操作或者操作次數(shù)達到一定數(shù)目時才會釋放GIL。所以,雖然CPython的線程庫直接封裝了系統(tǒng)的原生線程,但CPython整體作為一個進程,同一時間只會有一個獲得GIL的線程在跑,其他線程則處于等待狀態(tài)。這就造成了即使在多核CPU中,多線程也只是做著分時切換而已。
如果你的程序是CPU密集型,多個線程的代碼很有可能是線性執(zhí)行的。所以這種情況下多線程是雞肋,效率可能還不如單線程因為有上下文切換開銷。但是如果你的代碼是IO密集型,涉及到網(wǎng)絡(luò)、磁盤IO的任務(wù)都是IO密集型任務(wù),多線程可以明顯提高效率,例如多線程爬蟲,多線程文件處理等等
多線程爬蟲
多線程爬蟲的代碼實例
注: 以下代碼在python3下運行通過, python2版本差異較大,不能運行成功,如需幫助請下方留意。
# coding=utf-8 import threading, queue, time, urllib from urllib import request baseUrl = 'http://www.pythontab.com/html/pythonjichu/' urlQueue = queue.Queue() for i in range(2, 10): url = baseUrl + str(i) + '.html' urlQueue.put(url) #print(url) def fetchUrl(urlQueue): while True: try: #不阻塞的讀取隊列數(shù)據(jù) url = urlQueue.get_nowait() i = urlQueue.qsize() except Exception as e: break print ('Current Thread Name %s, Url: %s ' % (threading.currentThread().name, url)) try: response = urllib.request.urlopen(url) responseCode = response.getcode() except Exception as e: continue if responseCode == 200: #抓取內(nèi)容的數(shù)據(jù)處理可以放到這里 #為了突出效果, 設(shè)置延時 time.sleep(1) if __name__ == '__main__': startTime = time.time() threads = [] # 可以調(diào)節(jié)線程數(shù), 進而控制抓取速度 threadNum = 4 for i in range(0, threadNum): t = threading.Thread(target=fetchUrl, args=(urlQueue,)) threads.append(t) for t in threads: t.start() for t in threads: #多線程多join的情況下,依次執(zhí)行各線程的join方法, 這樣可以確保主線程最后退出, 且各個線程間沒有阻塞 t.join() endTime = time.time() print ('Done, Time cost: %s ' % (endTime - startTime))
運行結(jié)果:
1個線程時:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/8.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Done, Time cost: 8.182249069213867
2個線程時:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/8.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Done, Time cost: 4.0987958908081055
3個線程時:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-3, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-4, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-4, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Current Thread Name Thread-3, Url: http://www.pythontab.com/html/pythonjichu/8.html Done, Time cost: 2.287320137023926
通過調(diào)節(jié)線程數(shù)可以看到,執(zhí)行時間會隨著線程數(shù)的增加而縮短,抓取效率成正比增加。
總結(jié):
Python多線程在IO密集型任務(wù),多線程可以明顯提高效率,CPU密集型任務(wù)不適合使用多線程處理。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python基礎(chǔ)進階之海量表情包多線程爬蟲功能的實現(xiàn)
- python3爬蟲中多線程進行解鎖操作實例
- python3爬蟲GIL修改多線程實例講解
- python3爬蟲中多線程的優(yōu)勢總結(jié)
- python爬蟲開發(fā)之使用Python爬蟲庫requests多線程抓取貓眼電影TOP100實例
- python支持多線程的爬蟲實例
- python爬蟲中多線程的使用詳解
- Python 微信爬蟲完整實例【單線程與多線程】
- python面向?qū)ο蠖嗑€程爬蟲爬取搜狐頁面的實例代碼
- python爬蟲爬取快手視頻多線程下載功能
- php與python實現(xiàn)的線程池多線程爬蟲功能示例
- python 多線程爬取壁紙網(wǎng)站的示例
相關(guān)文章
FP-growth算法發(fā)現(xiàn)頻繁項集——發(fā)現(xiàn)頻繁項集
常見的挖掘頻繁項集算法有兩類,一類是Apriori算法,另一類是FP-growth。Apriori通過不斷的構(gòu)造候選集、篩選候選集挖掘出頻繁項集,需要多次掃描原始數(shù)據(jù),當(dāng)原始數(shù)據(jù)較大時,磁盤I/O次數(shù)太多,效率比較低下2021-06-06Python HTMLTestRunner測試報告view按鈕失效解決方案
這篇文章主要介紹了Python HTMLTestRunner測試報告view按鈕失效解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05根據(jù)DataFrame某一列的值來選擇具體的某一行方法
今天小編就為大家分享一篇根據(jù)DataFrame某一列的值來選擇具體的某一行方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07python中protobuf和json互相轉(zhuǎn)換應(yīng)用處理方法
protobuf目前有proto2和proto3兩個版本,本文所介紹的是基于proto3,在Python 3.6.9環(huán)境下運行,本文記錄一下python中protobuf和json的相互轉(zhuǎn)換的處理方法,感興趣的朋友跟隨小編一起看看吧2022-12-12