python爬虫之异步IO
来源:互联网 发布:香港手机网络运营商 编辑:程序博客网 时间:2024/06/07 05:26
在web请求非常多的情况下,异步IO往往效果和速率惊人。
#!/usr/bin/env python3# -*- coding: utf-8 -*-import requests,timestart_time=time.time()resp=requests.get(url='http://httpbin.org/headers')print(resp.text)print('用时:%s秒'%(time.time()-start_time))运行结果:
然后用aiohttp和asyncio进行异步IO试一下:
#!/usr/bin/env python3# -*- coding: utf-8 -*-import asyncio, aiohttp, timestart_time=time.time()async def request(url):async with aiohttp.ClientSession() as session:async with session.get(url) as resp:resp_text=await resp.read()print(resp_text.decode('utf-8'))loop=asyncio.get_event_loop()tasks=[request('http://httpbin.org/headers')]loop.run_until_complete(asyncio.wait(tasks))print('用时:%s秒'%(time.time()-start_time))运行结果:
虽然只有单任务,但是IO是通过交给操作系统处理的,速度也有一点的提升。那么在多任务的情况下会怎么样:
#!/usr/bin/env python3# -*- coding: utf-8 -*-import asyncio, aiohttp, timestart_time=time.time()response=[]async def fn(url):async with aiohttp.ClientSession() as session:async with session.get(url=url) as resp:response.append(await resp.read())loop=asyncio.get_event_loop()tasks=[asyncio.ensure_future(fn('http://www.baidu.com')) for x in range(500)]loop.run_until_complete(asyncio.wait(tasks))#print(response)print("用时%s秒" % (time.time()-start_time))使用协程访问500次百度,运行结果:
我们再用同步的requests试一下:
60s!
0 0
- python爬虫之异步IO
- python爬虫之异步XHR爬取
- Python之异步IO( asyncio) 协程
- python异步爬虫
- Python 异步网络爬虫
- 【Python】asyncio异步爬虫
- python 异步IO
- python 异步IO
- 【asyncio】python异步IO
- Python 异步网络爬虫 I
- Python并发编程之协程/异步IO
- Python网络编程之带select的异步IO
- 异步IO之----APC
- Python poll实现异步IO
- python异步IO和协程
- Python爬虫之分布式爬虫
- 异步网络爬虫的Python实现(1)
- 异步网络爬虫的Python实现(2)
- Dollar Days POJ 3181 完全背包+高精度
- linux下多线程的创建与等待详解
- Goblog--Arrays,slices(and strings):The mechanics of 'append'
- ext2文件系统
- Android Litepal数据库操作
- python爬虫之异步IO
- mybatis的select_resultMap_discriminator鉴别器
- python(2):使用python分析大日志文件思路及过程
- React-classnames库
- Jenkins进阶系列之——04Publish Over FTP Plugin插件
- 德银:iPhone 8或推迟到2018年上市
- Goblog--strings,bytes,runes and characters in Go
- BlockingQueue
- php的mb处理模块