前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >强大的异步爬虫 with aiohttp

强大的异步爬虫 with aiohttp

作者头像
小歪
发布2018-07-25 15:29:01
1.1K0
发布2018-07-25 15:29:01
举报
文章被收录于专栏:Python爬虫与算法进阶

看到现在网络上大多讲的都是requests、scrapy,却没有说到爬虫中的神器:aiohttp

aiohttp 介绍

aiohttp是什么,官网上有这样一句话介绍:Async HTTP client/server for asyncio and Python,翻译过来就是 asyncio和Python的异步HTTP客户端/服务器

主要特点是:

  1. 支持客户端和HTTP服务器。
  2. 无需使用Callback Hell即可支持Server WebSockets和Client WebSockets。
  3. Web服务器具有中间件,信号和可插拔路由。

emmmm,好吧,还是来看代码吧

Client example:

代码语言:javascript
复制
import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://httpbin.org/headers')
        print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

output:

代码语言:javascript
复制
{"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"Python/3.6 aiohttp/3.2.1"}}

Server example:

代码语言:javascript
复制
from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])

web.run_app(app)

output:

代码语言:javascript
复制
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)

aiohttp 与 requests

去翻一下官方文档 Client Quickstart,让我感觉非常熟悉,很多用法和requests相似。

代码语言:javascript
复制
async with aiohttp.ClientSession() as session:
    async with session.get('http://httpbin.org/get') as resp:
        print(resp.status)
        print(await resp.text())

首先,官方推荐使用ClientSession来管理会话,这不就是requests中的session吗?用法也类似,使用session.get()去发送get请求,返回的resp中就有我们所需要的数据了,用法也和requests一样,text()文本,.json()直接打印返回的json数据,headers什么的也一样,更多内容参考官方文档Response object

既然已经有requests了,那为什么还要说aiohttp了?重点来了,aiohttp是异步的。在python3.5中,加入了asyncio/await 关键字,使得回调的写法更加直观和人性化。而aiohttp是一个提供异步web服务的库,asyncio可以实现单线程并发IO操作。

requests写爬虫是同步的,是等待网页下载好才会执行下面的解析、入库操作,如果在下载网页时间太长会导致阻塞,使用multiprocessing或者 threading加速爬虫也是一种方法。

我们现在使用的aiohttp是异步的,简单来说,就是不需要等待,你尽管去下载网页就好了,我不用傻傻的等待你完成才进行下一步,我还有别的活要干。这样就极大的提高了下载网页的效率。

另外,Scrapy也是异步的,是基于Twisted事件驱动的。在任何情况下,都不要写阻塞的代码。阻塞的代码包括:

  1. 访问文件、数据库或者Web
  2. 产生新的进程并需要处理新进程的输出,如运行shell命令
  3. 执行系统层次操作的代码,如等待系统队列

代码实例

这里是使用aiohttp的一个爬虫实例

代码语言:javascript
复制
import asyncio

import aiohttp
from bs4 import BeautifulSoup

import logging

class AsnycGrab(object):

    def __init__(self, url_list, max_threads):

        self.urls = url_list
        self.results = {}
        self.max_threads = max_threads

    def __parse_results(self, url, html):

        try:
            soup = BeautifulSoup(html, 'html.parser')
            title = soup.find('title').get_text()
        except Exception as e:
            raise e

        if title:
            self.results[url] = title

    async def get_body(self, url):
        async with aiohttp.ClientSession() as session:
            async with session.get(url, timeout=30) as response:
                assert response.status == 200
                html = await response.read()
                return response.url, html

    async def get_results(self, url):
        url, html = await self.get_body(url)
        self.__parse_results(url, html)
        return 'Completed'

    async def handle_tasks(self, task_id, work_queue):
        while not work_queue.empty():
            current_url = await work_queue.get()
            try:
                task_status = await self.get_results(current_url)
            except Exception as e:
                logging.exception('Error for {}'.format(current_url), exc_info=True)

    def eventloop(self):
        q = asyncio.Queue()
        [q.put_nowait(url) for url in self.urls]
        loop = asyncio.get_event_loop()
        tasks = [self.handle_tasks(task_id, q, ) for task_id in range(self.max_threads)]
        loop.run_until_complete(asyncio.wait(tasks))
        loop.close()


if __name__ == '__main__':
    async_example = AsnycGrab(['http://edmundmartin.com',
               'https://www.udemy.com',
               'https://github.com/',
               'https://zhangslob.github.io/',
               'https://www.zhihu.com/'], 5)
    async_example.eventloop()
    print(async_example.results)

需要注意的是,你需要时刻在你的代码中使用异步操作,你如果在代码中使用同步操作,爬虫并不会报错,但是速度可能会受影响。

其他异步库

因为爬虫不仅仅只有下载这块,还会有操作数据库,这里提供两个异步库:aioredismotor

代码语言:javascript
复制
import asyncio
import aioredis

loop = asyncio.get_event_loop()

async def go():
    conn = await aioredis.create_connection(
        'redis://localhost', loop=loop)
    await conn.execute('set', 'my-key', 'value')
    val = await conn.execute('get', 'my-key')
    print(val)
    conn.close()
    await conn.wait_closed()
loop.run_until_complete(go())
# will print 'value'

文档:aioredis

代码语言:javascript
复制
import motor.motor_asyncio

client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')

db = client['test_database']
collection = db['test_collection']

async def do_insert():
    document = {'key': 'value'}
    result = await db.test_collection.insert_one(document)
    print('result %s' % repr(result.inserted_id))

async def do_find_one():
    document = await db.test_collection.find_one({'i': {'$lt': 1}})
    pprint.pprint(document)

文档:motor

本文仅仅介绍了aiohttp作为Client的用法, 有兴趣的朋友可以去研究下作为Server的用法,同样很强大。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-05-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python爬虫与算法进阶 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • aiohttp 介绍
  • aiohttp 与 requests
  • 代码实例
  • 其他异步库
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档