• 封装一个属于自己的网络异步爬虫框架


    目录:

    1:框架实现了什么东西

    2:框架如何定义网络池

    3:框架如何使用

    没错你直接pip3 install 就可以了

    pip install AioFastGet

     

    一、框架实现了什么东西

    整个框架都是采用异步方式进行的。

    二、框架如何定义网络池的

    使用了Redis的队列作为网络池概念。每次通过addurl 方法将要下载的一个url对象加入到整个队列中去,

    然后crawl_main方法会一直取请求,如果没有了要下载的url的话,就退出程序。

    三、框架如何使用

    from AioFastGet import RedisUrlPool
    import asyncio
    
    class GetFast(RedisUrlPool):
        def __init__(self):
            super(GetFast,self).__init__(host="192.168.100.79", db=0, password="abcde", port=6381)
            self._redisKey = "BaiduList"   ##指定网络池的key
            self._max_workers = 2          ##开始多少个任务
    
        async def load_url(self):
            """加载url item"""
            for i in range(10):
                # 访问http://www.httpbin.org/delay/2 是需要2秒才能返回内容。
                # 我们可以加载十个请求链接,按传统的方式是大概需要20多秒才能完成这10个请求
                # 可以自己拿起手表计算下,我们访问了10个请求花了多长的时间
                url_item = {"url":"http://www.httpbin.org/delay/2","backfunc":"parse_baidu"}
                await self._addurl(url_item)
    
    
        async def parse_baidu(self,r):
            """解析对应的回调函数"""
            print(r.keys())
            print("收到html长度:",len(r['html']))
    
        async def run(self):
            await self.load_url()     ##加载url
            await self.crawl_main()   ##启动爬虫程序
    
    
    if __name__ == '__main__':
        baidu = GetFast()
        loop = asyncio.get_event_loop()
        loop.run_until_complete(baidu.run())
    

    注意:当我们定义一个urlitem的时候,比如想发post请求,

    那么就在:{"url":"http://www.httpbin.org/delay/2","backfunc":"parse_baidu"} 加张一个 urlitem["method"] = "post"

    你加请求头或者代理的话都是往这个urlitem上加键值对。

    一共你可以加这几种:

    __url_keys = ["url", 'count', "backfunc", "method", "info", "proxy", "data", "headers", "timeout", "debug", "binary", "oargs", ]
    
  • 相关阅读:
    关于springboot项目使用yml类型的配置文件
    关于个人电脑连不上公司svn服务器,显示拒绝访问的错误
    改变思考问题的方式——SQL排序查询
    FreeMarker入门级
    个人电脑安装svn实录
    tomcat配置虚拟路径,可以解决实际开发中测试时前端访问后台电脑上的图片的问题
    springmvc的运行原理个人见解
    [CF915F] Imbalance Value of a Tree
    [CF768G] The Winds of Winter
    [BZOJ4241] 历史研究
  • 原文地址:https://www.cnblogs.com/hero799/p/16090162.html
Copyright © 2020-2023  润新知