網頁爬蟲 - python的多進程怎么配合requests
問題描述
這是單進程順序執行的代碼:
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個進程而已。
應該是這個原因。
相關文章:
1. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發現2. javascript - ...mapGetters和...mapState獲取到的state,怎么拿來在methods中操作?3. python - linux怎么在每天的凌晨2點執行一次這個log.py文件4. javascript - 在 vue里面用import引入js文件,結果為undefined5. 如何分別在Windows下用Winform項模板+C#,在MacOSX下用Cocos Application項目模板+Objective-C實現一個制作游戲的空的黑窗口?6. Java反射問題:為什么android.os.Message的recycleUnchecked方法不能通過反射獲取到?7. php如何獲取訪問者路由器的mac地址8. git - 使用淘寶npm安裝hexo出現問題?9. php - 微信開發驗證服務器有效性10. [python2]local variable referenced before assignment問題
