您的位置:首頁技術文章
文章詳情頁

網頁爬蟲 - python的多進程怎么配合requests

瀏覽:113日期:2022-06-27 18:08:43

問題描述

這是單進程順序執行的代碼:

import requests,time,os,randomdef img_down(url): with open('{}'.format(str(random.random())+os.path.basename(url)),'wb') as fob:fob.write(requests.get(url).content)urllist=[]with open('urllist.txt','r+') as u: for a in u.readlines():urllist.append(a.strip())s=time.clock()for i in range(len(urllist)): img_down(urllist[i])e=time.clock()print ('time: %d' % (e-s))

這是多進程的代碼:

from multiprocessing import Poolimport requests,os,time,randomdef img_down(url): with open('{}'.format(str(random.random())+os.path.basename(url)),'wb') as fob:fob.write(requests.get(url).content)if __name__=='__main__': urllist=[] with open('urllist.txt','r+') as urlfob:for s in urlfob.readlines(): urllist.append(s.strip()) s=time.clock() p=Pool() for i in range(len(urllist)):p.apply_async(img_down,args=(urllist[i],)) p.close() p.join() e=time.clock()print ('time: {}'.format(e-s))

但是單進程和多進程花費的時間幾乎沒區別,問題大概是requests阻塞IO,請問理解的對不對,代碼該怎么修改達到多進程的目的?謝謝!

問題解答

回答1:

寫文件的瓶頸在磁盤IO,并不在CPU,你并行并沒有多大作用,你可以試試不要寫入文件再對比時間

回答2:

Pool 不帶參數的話 是采用 os.cpu_count() or 1如果是單核CPU,或者采集不到數量 就只有1個進程而已。

應該是這個原因。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区