Python多線程爬蟲簡單樣本

來源:互聯網
上載者:User
python是支援多線程的,主要是通過thread和threading這兩個模組來實現的。thread模組是比較底層的模組,threading模組是對thread做了一些封裝的,可以更加方便的使用。

雖然python的多線程受GIL限制,並不是真正的多線程,但是對於I/O密集型計算還是能明顯提高效率,比如說爬蟲。

下面用一個執行個體來驗證多線程的效率。代碼只涉及頁面擷取,並沒有解析出來。

# -*-coding:utf-8 -*-import urllib2, timeimport 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__':  # 構造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() # 等待線程終止,等子線程執行完後再執行父線程

以上就是本文的全部內容,希望對大家的學習有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.