asyncio/aiohttp 的协程爬虫

1.asyncio是一个写协程的。

1.导包

import asyncio

2.1.创建方法(里面带休眠)

@asyncio.coroutine
def hello():
    print('Hello world')
    yield from asyncio.sleep(1)
    print('Hello again!')

2.2 方法也可以这样创建

async def hello():
    print("Hello world!")
    r = await asyncio.sleep(1)
    print("Hello again!")

3.运行代码

loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

2.aiohttp–》asyncio对它进行了封装,用aiohttp进行网络访问时,会自动yield跳转到其他任务执行。

1.导包

import asyncio
import aiohttp

2.写方法

async def open():
    async with aiohttp.request('get', 'http://blog.csdn.net/u014595019/article/details/52295642') as f:
        a = await f.text()
        print(a)

3.开启协程

loop = asyncio.get_event_loop()
tasks = [open(), open()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

这是aiohttp最基本的用法了 请求头, 代理等的添加可以参考这篇blog
aiohttp的一些细节

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值