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

编程入门 行业动态 更新时间:2024-10-11 17:25:32

sanic+aiohttp<a href=https://www.elefans.com/category/jswz/34/1770264.html style=爬虫demo(爬图片,新闻,数据)"/>

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:  # 创建sessionasync 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 = "/{}"try:myloop.create_task(getsource(url.format(i)))  # 添加任务到事件循环except Exception as e:passreturn text('爬取成功')if __name__ == "__main__":#用gunicorn部署命令# gunicorn api_pachong:app --bind 0.0.0.0:8090 --workers=4 --worker-class sanic.worker.GunicornWorkerapp.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 textapp = Sanic(__name__)@app.route('/')
async def pars(request):async with aiohttp.ClientSession() as set:count = 0url = '/{}.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 += 1img_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 responseapp = 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:continuep = 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 = '/'Loop = request.app.loopLoop.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/news/201810/923880.html#pvareaid=102624
文本:[汽车之家 新闻]  日前,我们从官方渠道获悉,新款奇瑞瑞虎5x 1.5L款将在10月27日全面开启预售。作为奇瑞汽车的核心车型,新车除了将搭载1.5...标题:广汽古惠南:未来或推方形/球形的汽车
链接://www.autohome/news/201810/923883.html#pvareaid=102624
文本:[汽车之家 新闻]  在10月19日举行的世界智能网联汽车大会上,广汽新能源总经理古惠南分享了他对未来汽车形态上的构想,他表示,未来汽车将不会只有轿车...标题:售19.28万起 长安福特蒙迪欧智控版上市"""
爬取新闻

 

转载于:.html

更多推荐

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

本文发布于:2024-02-12 00:21:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1684560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:爬虫   数据   图片   新闻   sanic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!