• sanic+aiohttp爬虫demo(爬图片,新闻,数据)


    直接上代码,都是很简单的一些demo,爬取的网站,都没有什么加密措施,所以应该不涉及违法数据,哈哈

    1.爬取网页数据(aiohttp+sanic+scrapy+xpath解析html)

    from sanic import Sanic
    import aiohttp  # 导入aiohttp
    from sanic.response import text
    from scrapy import Selector  # 导入html解析模块
    
    app = Sanic(__name__)
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"}
    
    
    async def getsource(url):
        conn = aiohttp.TCPConnector(verify_ssl=False)  # 防止ssl报错
        async with aiohttp.ClientSession(connector=conn) as session:  # 创建session
            async with session.get(url, headers=headers, timeout=0) as req:  # 获得请求
                if req.status == 200:  # 判断请求码
                    source = await req.text()  # 使用await关键字获取返回结果
    
                    print('爬取的文章')
                    sel = Selector(text=source)
                    l = []
                    a = sel.xpath('//ol[@class="breadcrumb"]/li[@class="active"]/text()').extract_first()
                    b = sel.xpath('//ul[@class="nav nav-tabs"]/li[@class="active"]/a/text()').extract_first()
                    c = sel.xpath('//span[@class="course-view"]/text()').extract_first()
                    l.append((a, b, c))
                    print(l)
                else:
                    print("访问失败")
    
    
    @app.route('/')
    async def sanic_hello(request):
        myloop = request.app.loop  # 创建事件循环
        # == event_loop = asyncio.get_event_loop()
        for i in range(1, 10):
            url = "https://edu.hellobi.com/course/{}"
            try:
                myloop.create_task(getsource(url.format(i)))  # 添加任务到事件循环
            except Exception as e:
                pass
        return text('爬取成功')
    
    
    if __name__ == "__main__":
        #用gunicorn部署命令
        # gunicorn api_pachong:app --bind 0.0.0.0:8090 --workers=4 --worker-class sanic.worker.GunicornWorker
        app.run(host='127.0.0.1', port=8090, workers=8)
    
    
    #""
    爬取的文章
    [('微软 BI 实战入门系列【持续更新中】', '课程概览', '1742 人学习')]
    爬取的文章
    [('MS SQL数据库入门及初级BI教程', '课程概览', '1667 人学习')]
    爬取的文章
    [('IBM Cognos 中级视频教程 【模型和报表教程】', '课程概览', '1227 人学习')]
    爬取的文章
    [('咖啡姐 BIEE 11G 精品入门视频教程【新手必看】', '课程概览', '2626 人学习')]
    爬取的文章
    [('BI基础知识漫谈【献给所以热爱商业智能的朋友】', '课程概览', '2398 人学习')]
    爬取的文章
    [('数据仓库精品教程【特点,数据仓库和ETL设计思想、架构(自上而下、自下而上)、常用概念】', '课程概览', '3856 人学习')]
    爬取的文章
    [('IBM Cognos 初级教程 【入门必学】', '课程概览', '2520 人学习')]
    爬取的文章
    [('Oracle BIEE 提高视频教程【时间序列函数,多表头制作,数据同步】', '课程概览', '1151 人学习')]
    爬取的文章
    [('微软商业智能实战入门及提高视频教程', '课程概览', '249 人学习')]
    """
    翻页爬去简单网页

    2.爬取网页图片,并下载到本地aiohttp+sanic+BeautifulSoup解析html

    import aiohttp
    import requests
    from sanic import Sanic
    from bs4 import BeautifulSoup
    from sanic.response import text
    
    app = Sanic(__name__)
    
    
    @app.route('/')
    async def pars(request):
        async with aiohttp.ClientSession() as set:
            count = 0
            url = 'http://www.moko.cc/channels/post/151/{}.html'
            for i in range(1, 2):
                try:
                    async with set.get(url.format(i))as respon:  # 异步发送请求
                        res = await respon.read()
                        soup = BeautifulSoup(res, 'html.parser')  # 解析网页
                        div_list = soup.find_all(name='div', attrs={'class': "cover"})  # 找到div标签所属的所有标签
                        for div in div_list:  # 循环读取div标签内容
                            img_l = div.find(name='img')  # 找到img标签
                            src2 = img_l.attrs.get('src2')  # 获取src图片链接
                            if src2:
                                count += 1
                                img_path = 'img/' + str(count) + ".jpg"  # 拼接图片存储路径以及文件名称
                                re_img = requests.get(src2)  # 下载图片
                                with open(img_path, 'wb')as f:  # 打开图片,存储
                                    f.write(re_img.content)  # 获取图片内容
                        print('完成第{}页'.format(i))
                except Exception as e:
                    print(e)
            return text('爬取成功')
    
    
    if __name__ == '__main__':
        app.run(host="127.0.0.1", port=8811, workers=8)
    翻页爬取网页图片并下载

    3.爬取新闻,信息存储到本地txt文件中(aiohttp+sanic+BeautifulSoup解析html)

    import aiohttp
    from sanic import Sanic
    from bs4 import BeautifulSoup
    from sanic import response
    
    app = Sanic(__name__)
    
    
    async def get_content(url):
        async with aiohttp.ClientSession() as session:
            # for i in range(1,4):
            async with session.get(url) as ret:
                res = await ret.text()
                # print(url)
                # print(res)
                soup = BeautifulSoup(res, 'html.parser')
                div = soup.find(name="div", attrs={"id": "auto-channel-lazyload-article"})
                li_list = div.find_all(name="li")
                for li in li_list:
                    title = li.find(name="h3")
                    if not title:
                        continue
                    p = li.find(name="p")
                    a = li.find(name="a")
    
                    # print(title.text)
                    # print(a.attrs.get("href"))
                    # print(p.text)
                    with open('sanic_log.txt', 'a')as f:  # 把信息存储到sanic_log文本中
                        f.write('标题:' + title.text + '
    ')
                        f.write('链接:' + a.attrs.get("href") + '
    ')
                        f.write('文本:' + p.text)
    
    
    @app.route('/index')
    async def index(request):
        url = 'https://www.autohome.com.cn/news/'
        Loop = request.app.loop
        Loop.create_task(get_content(url))
        return response.text('hello sprider')
    
    
    if __name__ == '__main__':
        app.run(host="127.0.0.1", port=8811, workers=8)
        
    #"""
    标题:10月27日预售 新款瑞虎5x更多信息曝光
    链接://www.autohome.com.cn/news/201810/923880.html#pvareaid=102624
    文本:[汽车之家 新闻]  日前,我们从官方渠道获悉,新款奇瑞瑞虎5x 1.5L款将在10月27日全面开启预售。作为奇瑞汽车的核心车型,新车除了将搭载1.5...标题:广汽古惠南:未来或推方形/球形的汽车
    链接://www.autohome.com.cn/news/201810/923883.html#pvareaid=102624
    文本:[汽车之家 新闻]  在10月19日举行的世界智能网联汽车大会上,广汽新能源总经理古惠南分享了他对未来汽车形态上的构想,他表示,未来汽车将不会只有轿车...标题:售19.28万起 长安福特蒙迪欧智控版上市
    
    """
    爬取新闻
  • 相关阅读:
    整理牙刷
    color 圆盘染色
    数论の一波流[长期更新]
    生成树
    一维黑白棋
    Factorials
    平面分割问题
    poj1183 反正切函数
    烽火传递
    校门外的树
  • 原文地址:https://www.cnblogs.com/zzy-9318/p/9817876.html
Copyright © 2020-2023  润新知