網頁爬蟲 - 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. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. 在應用配置文件 app.php 中找不到’route_check_cache’配置項3. html按鍵開關如何提交我想需要的值到數據庫4. objective-c - 自定義導航條為類似美團的搜索欄樣式5. ios - vue-cli開發項目webstrom會在stylus樣式報錯,飆紅,請大神幫忙6. html5 - 用Egret寫的小游戲,怎么分享到微信呢?7. css - BEM 中塊(Block)有木有什么標準 何時決定一個部分提取為塊而不是其父級的元素呢(Element)?~8. css3 - 怎么感覺用 rem 開發的不多啊9. css - width設置為100%之后列表無法居中10. python - 在pyqt中做微信的機器人,要在表格中顯示微信好友的名字,卻顯示不出來,怎么解決?
