异步协程不太了解的话可以去看我上篇博客:https://www.cnblogs.com/Red-Sun/p/16934843.html

PS:本博客是个人笔记分享,不需要扫码加群或必须关注什么的(如果外站需要加群或关注的可以直接去我主页查看)

欢迎大家光临ヾ(≧▽≦*)o我的博客首页https://www.cnblogs.com/Red-Sun/

1.requests请求

# -*- coding: utf-8 -*-
# @Time : 2022/12/6 16:03
# @Author : 红后
# @Email : not_enabled@163.com
# @blog : https://www.cnblogs.com/Red-Sun
# @File : 实例1.py
# @Software: PyCharm
import aiohttp, asyncio async def aiohttp_requests(url): # aiohttp的requests函数
async with aiohttp.request("GET", url=url) as response:
return await response.text(encoding='UTF-8') async def main(): # 主函数用于异步函数的启动
url = 'https://www.baidu.com'
html = await aiohttp_requests(url) # await修饰异步函数
print(html) if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

2.session请求

GET:

# -*- coding: utf-8 -*-
# @Time : 2022/12/6 16:33
# @Author : 红后
# @Email : not_enabled@163.com
# @blog : https://www.cnblogs.com/Red-Sun
# @File : 实例2.py
# @Software: PyCharm
import aiohttp, asyncio async def aiohttp_requests(url): # aiohttp的requests函数
async with aiohttp.ClientSession() as session: # 声明了一个支持异步的上下文管理器
async with session.get(url) as response:
return await response.text(encoding='UTF-8') async def main(): # 主函数用于异步函数的启动
url = 'https://www.baidu.com'
html = await aiohttp_requests(url) # await修饰异步函数
print(html) if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())



其中aiohttp还有post,put, delete...等一系列请求(PS:一般情况下只需要创建一个session,然后使用这个session执行所有的请求。)

PSOT:传参

async def aiohttp_requests(url):  # aiohttp的requests函数
async with aiohttp.ClientSession() as session:
data = {'key': 'value'}
async with session.post(url=url, data=data) as response:
return await response.text(encoding='UTF-8')

PS:这种传参传递的数据将会被转码,如果不想被转码可以直接提交字符串data=str(data)

附:关于session请求数据修改操作

1.cookies

自定义cookies应该放在ClientSession中,而不是session.get()中

async def aiohttp_requests(url):  # aiohttp的requests函数
cookies = {'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}
async with aiohttp.ClientSession(cookies=cookies) as session:
async with session.get(url) as response:
return await response.text(encoding='UTF-8')

2.headers

放在自定义的headers跟正常的requests一样放在session.get()中

async def aiohttp_requests(url):  # aiohttp的requests函数
async with aiohttp.ClientSession() as session:
headers = {'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}
async with session.get(url=url, headers=headers) as response:
return await response.text(encoding='UTF-8')

3.timeout

默认响应时间为5分钟,通过timeout可以重新设定,其放在session.get()中

async def aiohttp_requests(url):  # aiohttp的requests函数
async with aiohttp.ClientSession() as session:
async with session.get(url=url, timeout=60) as response:
return await response.text(encoding='UTF-8')

4.proxy

当然代理也是支持的在session.get()中配置

async def aiohttp_requests(url):  # aiohttp的requests函数
async with aiohttp.ClientSession() as session:
async with session.get(url=url, proxy="http://some.proxy.com") as response:
return await response.text(encoding='UTF-8')

需要授权的代理

async def aiohttp_requests(url):  # aiohttp的requests函数
async with aiohttp.ClientSession() as session:
proxy_auth = aiohttp.BasicAuth('user', 'pass') # 用户,密码
async with session.get(url=url, proxy="http://some.proxy.com", proxy_auth=proxy_auth) as response:
return await response.text(encoding='UTF-8')

或者

async def aiohttp_requests(url):  # aiohttp的requests函数
async with aiohttp.ClientSession() as session:
async with session.get(url=url, proxy='http://user:pass@some.proxy.com') as response:
return await response.text(encoding='UTF-8')

报错处理

错误:RuntimeError: Event loop is closed



报错原因是使用了asyncio.run(main())来运行程序

看到别个大佬的总结是asyncio.run()会自动关闭循环,并且调用_ProactorBasePipeTransport.__del__报错, 而asyncio.run_until_complete()不会。

第一种解决方法换成如下代码运行

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

第二种重写方法以保证run()的运行

from functools import wraps

from asyncio.proactor_events import _ProactorBasePipeTransport

def silence_event_loop_closed(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except RuntimeError as e:
if str(e) != 'Event loop is closed':
raise
return wrapper _ProactorBasePipeTransport.__del__ = silence_event_loop_closed(_ProactorBasePipeTransport.__del__)

Python异步爬虫(aiohttp版)的更多相关文章

  1. python异步爬虫

    本文主要包括以下内容 线程池实现并发爬虫 回调方法实现异步爬虫 协程技术的介绍 一个基于协程的异步编程模型 协程实现异步爬虫 线程池.回调.协程 我们希望通过并发执行来加快爬虫抓取页面的速度.一般的实 ...

  2. python3异步爬虫 ——aiohttp模板使用

    一.简单使用和讲解 import aiohttp import asyncio async def fetch(client): async with client.get('http://httpb ...

  3. python 基于aiohttp的异步爬虫实战

    钢铁知识库,一个学习python爬虫.数据分析的知识库.人生苦短,快用python. 之前我们使用requests库爬取某个站点的时候,每发出一个请求,程序必须等待网站返回响应才能接着运行,而在整个爬 ...

  4. 利用aiohttp制作异步爬虫

      asyncio可以实现单线程并发IO操作,是Python中常用的异步处理模块.关于asyncio模块的介绍,笔者会在后续的文章中加以介绍,本文将会讲述一个基于asyncio实现的HTTP框架--a ...

  5. [python]新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  6. Python实现基于协程的异步爬虫

    一.课程介绍 1. 课程来源 本课程核心部分来自<500 lines or less>项目,作者是来自 MongoDB 的工程师 A. Jesse Jiryu Davis 与 Python ...

  7. 用Python写网络爬虫 第二版

    书籍介绍 书名:用 Python 写网络爬虫(第2版) 内容简介:本书包括网络爬虫的定义以及如何爬取网站,如何使用几种库从网页中抽取数据,如何通过缓存结果避免重复下载的问题,如何通过并行下载来加速数据 ...

  8. python爬虫beta版之抓取知乎单页面回答(low 逼版)

    闲着无聊,逛知乎.发现想找点有意思的回答也不容易,就想说要不写个爬虫帮我把点赞数最多的给我搞下来方便阅读,也许还能做做数据分析(意淫中--) 鉴于之前用python写爬虫,帮运营人员抓取过京东的商品品 ...

  9. 初识python 之 爬虫:使用正则表达式爬取“糗事百科 - 文字版”网页数据

    初识python 之 爬虫:使用正则表达式爬取"古诗文"网页数据 的兄弟篇. 详细代码如下: #!/user/bin env python # author:Simple-Sir ...

  10. 深入理解 Python 异步编程(上)

    http://python.jobbole.com/88291/ 前言 很多朋友对异步编程都处于"听说很强大"的认知状态.鲜有在生产项目中使用它.而使用它的同学,则大多数都停留在知 ...

随机推荐

  1. Logstash集成GaussDB(高斯DB)数据到Elasticsearch

    GaussDB 简介 GaussDB 数据库分为 GaussDB T 和 GaussDB A,分别面向 OLTP 和 OLAP 的业务用户. GaussDB T 数据库是华为公司全自研的分布式数据库, ...

  2. Elasticsearch:正确使用regexp搜索

  3. Node.js(五)学生管理CRUD

    npm init -y(初始化项目) npm install express(引入express) npx express-generator -e(自动生成模板.添加对 ejs 模板引擎的支持) n ...

  4. C++面向对象编程之point-like classes的智能指针和迭代器、function-like classes即仿函数

    1.智能指针 智能指针里面包含其他指针的形式和 委托 感觉比较像; 智能指针一定都需要重载 * 和 -> 操作符 ; 这个符号它作用后还能再继续作用下去; 2.迭代器: 这里主要关注 * 和 - ...

  5. 大数据技术之HBase原理与实战归纳分享-中

    @ 目录 底层原理 Master架构 RegionServer架构 Region/Store/StoreFile/Hfile之间的关系 写流程 写缓存刷写 读流程 文件合并 分区 JAVA API编程 ...

  6. 工厂方法在Spring源码中的运用

    我们都知道Spring中IOC是使用的工厂模式,但是对于实现细节就一知半解了,今天这篇文章就带大家解读Spring中是如何使用工厂模式的. 在上篇文章中我们懂了什么是工厂模式,这篇文章就带着学过的概念 ...

  7. 【软件学习】怎么在Word里面设置MathType分隔符,使公式按照章节自动编号

    前提 确保已安装好了MathType,且在设置为Word加载项 若没有安装或设置为加载项,请转至博客另一篇文章: [软件学习]如何下载安装Mathtype,并将其加载至Word 第一步 点击MathT ...

  8. 2022-09-11-Typecho_RSS优化显示全文

    layout: post cid: 26 title: Typecho RSS优化显示全文 slug: 26 date: 2022/09/11 15:53:38 updated: 2022/09/11 ...

  9. 商品期货通用模型JF1

    更多精彩内容,欢迎关注公众号:数量技术宅,也可添加技术宅个人微信号:sljsz01,与我交流. 行情不确定性加剧 回顾2022年上半年的期货市场行情,在一个个宏观事件的不断冲击下,期货市场的不确定性加 ...

  10. 常用RE对照表——敬请期待!!!

    .* #任意长度任意字符