網頁爬蟲 - 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. html5 - ElementUI table中el-table-column怎么設置百分比顯示。2. python - 使用readlines()方法讀取文件內容后,再用for循環遍歷文件與變量匹配時出現疑難?3. 對mysql某個字段監控的功能4. css3 - less或者scss 顏色計算的知識應該怎么學?或者在哪里學?5. 注冊賬戶文字不能左右分離6. javascript - table列過多,有什么插件可以提供列排序和選擇顯示列的功能7. css - 網頁div區塊 像蘋果一樣可左右滑動 手機與電腦8. javascript - 數組的過濾和渲染9. html - vue項目中用到了elementUI問題10. JavaScript事件
