Python多線程爬蟲簡單示例
python是支持多線程的,主要是通過thread和threading這兩個模塊來實現(xiàn)的。thread模塊是比較底層的模塊,threading模塊是對thread做了一些包裝的,可以更加方便的使用。
雖然python的多線程受GIL限制,并不是真正的多線程,但是對于I/O密集型計算還是能明顯提高效率,比如說爬蟲。
下面用一個實例來驗證多線程的效率。代碼只涉及頁面獲取,并沒有解析出來。
# -*-coding:utf-8 -*-
import urllib2, time
import threading
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)
def open_url(url):
request = urllib2.Request(url)
html = urllib2.urlopen(request).read()
print len(html)
return html
if __name__ == '__main__':
# 構(gòu)造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個訪問速度比較慢的網(wǎng)頁,一般方式耗時50s,多線程耗時10s。
多線程代碼解讀:
# 創(chuàng)建線程類,繼承Thread類
class MyThread(threading.Thread):
def __init__(self, func, args):
threading.Thread.__init__(self) # 調(diào)用父類的構(gòu)造函數(shù)
self.args = args
self.func = func
def run(self): # 線程活動方法
apply(self.func, self.args)
threadList = [MyThread(open_url, (url,)) for url in urlList] # 調(diào)用線程類創(chuàng)建新線程,返回線程列表
for t in threadList:
t.setDaemon(True) # 設(shè)置守護(hù)線程,父線程會等待子線程執(zhí)行完后再退出
t.start() # 線程開啟
for i in threadList:
i.join() # 等待線程終止,等子線程執(zhí)行完后再執(zhí)行父線程
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
Python使用py2neo操作圖數(shù)據(jù)庫neo4j的方法詳解
這篇文章主要介紹了Python使用py2neo操作圖數(shù)據(jù)庫neo4j的方法,結(jié)合實例形式詳細(xì)分析了Python使用py2neo操作圖數(shù)據(jù)庫neo4j的具體步驟、原理、相關(guān)使用技巧與操作注意事項,需要的朋友可以參考下2020-01-01
Python?pyecharts?Boxplot箱線圖的實現(xiàn)
本文主要介紹了Python?pyecharts?Boxplot箱線圖的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
修改Python?pip下載包的默認(rèn)路徑詳細(xì)步驟記錄
這篇文章主要介紹了如何修改pip的默認(rèn)安裝路徑以釋放C盤空間,特別是針對機器學(xué)習(xí)相關(guān)的大型包,可以將pip的安裝位置更改為其他目錄,需要的朋友可以參考下2025-03-03
通過pycharm的database設(shè)置進(jìn)行數(shù)據(jù)庫的可視化方式
這篇文章主要介紹了通過pycharm的database設(shè)置進(jìn)行數(shù)據(jù)庫的可視化方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09

