国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python3多線程爬蟲實例講解代碼

2020-02-16 11:29:22
字體:
來源:轉載
供稿:網友

多線程概述

多線程使得程序內部可以分出多個線程來做多件事情,充分利用CPU空閑時間,提升處理效率。python提供了兩個模塊來實現多線程thread 和threading ,thread 有一些缺點,在threading 得到了彌補。并且在Python3中廢棄了thread模塊,保留了更強大的threading模塊。

使用場景

在python的原始解釋器CPython中存在著GIL(Global Interpreter Lock,全局解釋器鎖),因此在解釋執行python代碼時,會產生互斥鎖來限制線程對共享資源的訪問,直到解釋器遇到I/O操作或者操作次數達到一定數目時才會釋放GIL。所以,雖然CPython的線程庫直接封裝了系統的原生線程,但CPython整體作為一個進程,同一時間只會有一個獲得GIL的線程在跑,其他線程則處于等待狀態。這就造成了即使在多核CPU中,多線程也只是做著分時切換而已。

如果你的程序是CPU密集型,多個線程的代碼很有可能是線性執行的。所以這種情況下多線程是雞肋,效率可能還不如單線程因為有上下文切換開銷。但是如果你的代碼是IO密集型,涉及到網絡、磁盤IO的任務都是IO密集型任務,多線程可以明顯提高效率,例如多線程爬蟲,多線程文件處理等等

多線程爬蟲

多線程爬蟲的代碼實例

注: 以下代碼在python3下運行通過, python2版本差異較大,不能運行成功,如需幫助請下方留意。

# coding=utf-8import threading, queue, time, urllibfrom urllib import requestbaseUrl = '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:   #不阻塞的讀取隊列數據   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:   #抓取內容的數據處理可以放到這里   #為了突出效果, 設置延時   time.sleep(1)if __name__ == '__main__': startTime = time.time() threads = [] # 可以調節線程數, 進而控制抓取速度 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的情況下,依次執行各線程的join方法, 這樣可以確保主線程最后退出, 且各個線程間沒有阻塞  t.join() endTime = time.time() print ('Done, Time cost: %s ' % (endTime - startTime))

運行結果:

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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 华容县| 眉山市| 双辽市| 牡丹江市| 岳普湖县| 黄梅县| 龙川县| 静乐县| 侯马市| 衡阳市| 绩溪县| 防城港市| 沙坪坝区| 郧西县| 兴仁县| 金川县| 错那县| 莱阳市| 平江县| 泗水县| 平潭县| 黎平县| 星子县| 贺兰县| 克拉玛依市| 长岭县| 砀山县| 晴隆县| 宜宾县| 南投县| 柘城县| 连州市| 惠水县| 当雄县| 瓮安县| 辽宁省| 禹州市| 如东县| 安仁县| 子长县| 大名县|