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 + '\n')
                    f.write('鏈接:' + a.attrs.get("href") + '\n')
                    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萬起 長安福特蒙迪歐智控版上市

"""
爬取新聞

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM