Python异步爬虫(aiohttp版)
异步协程不太了解的话可以去看我上篇博客: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版)的更多相关文章
- python异步爬虫
本文主要包括以下内容 线程池实现并发爬虫 回调方法实现异步爬虫 协程技术的介绍 一个基于协程的异步编程模型 协程实现异步爬虫 线程池.回调.协程 我们希望通过并发执行来加快爬虫抓取页面的速度.一般的实 ...
- python3异步爬虫 ——aiohttp模板使用
一.简单使用和讲解 import aiohttp import asyncio async def fetch(client): async with client.get('http://httpb ...
- python 基于aiohttp的异步爬虫实战
钢铁知识库,一个学习python爬虫.数据分析的知识库.人生苦短,快用python. 之前我们使用requests库爬取某个站点的时候,每发出一个请求,程序必须等待网站返回响应才能接着运行,而在整个爬 ...
- 利用aiohttp制作异步爬虫
asyncio可以实现单线程并发IO操作,是Python中常用的异步处理模块.关于asyncio模块的介绍,笔者会在后续的文章中加以介绍,本文将会讲述一个基于asyncio实现的HTTP框架--a ...
- [python]新手写爬虫v2.5(使用代理的异步爬虫)
开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...
- Python实现基于协程的异步爬虫
一.课程介绍 1. 课程来源 本课程核心部分来自<500 lines or less>项目,作者是来自 MongoDB 的工程师 A. Jesse Jiryu Davis 与 Python ...
- 用Python写网络爬虫 第二版
书籍介绍 书名:用 Python 写网络爬虫(第2版) 内容简介:本书包括网络爬虫的定义以及如何爬取网站,如何使用几种库从网页中抽取数据,如何通过缓存结果避免重复下载的问题,如何通过并行下载来加速数据 ...
- python爬虫beta版之抓取知乎单页面回答(low 逼版)
闲着无聊,逛知乎.发现想找点有意思的回答也不容易,就想说要不写个爬虫帮我把点赞数最多的给我搞下来方便阅读,也许还能做做数据分析(意淫中--) 鉴于之前用python写爬虫,帮运营人员抓取过京东的商品品 ...
- 初识python 之 爬虫:使用正则表达式爬取“糗事百科 - 文字版”网页数据
初识python 之 爬虫:使用正则表达式爬取"古诗文"网页数据 的兄弟篇. 详细代码如下: #!/user/bin env python # author:Simple-Sir ...
- 深入理解 Python 异步编程(上)
http://python.jobbole.com/88291/ 前言 很多朋友对异步编程都处于"听说很强大"的认知状态.鲜有在生产项目中使用它.而使用它的同学,则大多数都停留在知 ...
随机推荐
- Beats:在Docker里运行Filebeat
- 4.Gitlab CI 与 Kubernetes 的结合
参考网址:https://www.qikqiak.com/post/gitlab-ci-k8s-cluster-feature/
- 条件期望:Conditional Expectation 举例详解之入门之入门之草履虫都说听懂了
我知道有很多人理解不了 "条件期望" (Conditional Expectation) 这个东西,有的时候没看清把随机变量看成事件,把 \(\sigma\)-algebra 看成 ...
- 非Navicat破解延长14天试用时间
延长Navicat使用时长 Navicat作为一套多连接数据库开发工具,十分好用,购买正版太过昂贵,破解版过于麻烦,有时候还会有安全问题,好在我们有14天的试用时间,我们可以从这个方面入手 对于有能力 ...
- MybatisPlus生成主键策略方法
MybatisPlus生成主键策略方法 全局id生成策略[因为是全局id所以不推荐] SpringBoot集成Mybatis-Plus 在yaml配置文件中添加MP配置 mybatis-plus: g ...
- String内建函数
int length():返回字符串的长度: return value.lengthchar charAt(int index): 返回某索引处的字符return value[index]boolea ...
- JVM中的堆
堆 内存结构 堆的核心概念 <java虚拟机规范>中对java堆的描述是:所有的对象实例以及数组都应当在运行时分配在堆上. 一个JVM实例只存在一个堆内存(就是new 出来一个对象),ja ...
- 分享个好东西 - 两行前端代码搞定bilibili链接转视频
只需要在您的要解析B站视频的页面的</body>前面加上下面两行代码即可,脚本会在客户端浏览器里解析container所匹配到的容器里的B站超链接 (如果不是外围有a标签的超链接只是纯粹的 ...
- 【MySQL】03_数据类型
MySQL 中的数据类型 类型 类型举例 整数类型 TINYINT.SMALLINT.MEDIUMINT.INT(或INTEGER).BIGINT 浮点类型 FLOAT.DOUBLE 定点数类型 DE ...
- 2流高手速成记(之五):Springboot整合Shiro实现安全管理
废话不多说,咱们直接接上回 上一篇我们讲了如何使用Springboot框架整合Nosql,并于文章最后部分引入了服务端Session的概念 而早在上上一篇中,我们则已经讲到了如何使用Springboo ...