• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
百里丶落云
Gee,gee,baby,baby
            管理     
爬虫----异步---高性能爬虫----aiohttp 和asycio 的使用

前情提要:

  首先膜拜loco大佬

    肯定有人像我一样.不会异步,发一下.

 

一:性能比对

    多进程,多线程,(这里不建议使用,太消耗性能)

    进程池和线程池 (可以适当的使用)

    单线程+异步协程   (推荐使用)

二:案例演示

    1->1: 普通的啥也不用的

  

    1->2:

               

 

      2->1:

      使用线程池

      

      2->2:结果

    

三:异步协程

    1: 协程的参数设定

 

       2:协程的简单使用

 

       3:task的使用

 

4:future 的使用

5:

回调函数的使用

四:支持异步请求网络的模块: aiohttp

 

import aiohttp
import asyncio

async def get_page(url):             
    async with aiohttp.ClientSession() as session:      #with 前面都要加async
        async with await session.get(url=url) as response:  # 有io阻塞的都要加await 
挂起 page_text = await response.text() #read() json() print(page_text) start = time.time() urls = [ 'http://127.0.0.1:5000/bobo', 'http://127.0.0.1:5000/jay', 'http://127.0.0.1:5000/tom', 'http://127.0.0.1:5000/bobo', 'http://127.0.0.1:5000/jay', 'http://127.0.0.1:5000/tom', 'http://127.0.0.1:5000/bobo', 'http://127.0.0.1:5000/jay', 'http://127.0.0.1:5000/tom' ] tasks = [] loop = asyncio.get_event_loop() for url in urls: c = get_page(url) task = asyncio.ensure_future(c) tasks.append(task) loop.run_until_complete(asyncio.wait(tasks)) print('总耗时:',time.time()-start)

 

年与时驰,意与日去,遂成枯落, 多不接世,悲守穷庐,将复何及。
posted on 2019-05-25 17:31  百里丶落云  阅读(376)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3