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/ 前言 很多朋友对异步编程都处于"听说很强大"的认知状态.鲜有在生产项目中使用它.而使用它的同学,则大多数都停留在知 ...
随机推荐
- Elasticsearch:单节点数据迁移
Elasticsearch数据迁移:windows单节点迁移到windows 将源数据中的ES安装目录下的data/nodes目录整体拷贝到目标ES的对应目录下 迁移前请备份:迁移后需要重启ES: E ...
- Elasticsearch中的一些重要概念:cluster, node, index, document, shards及replica
首先,我们来看下一下如下的这个图: Cluster Cluster也就是集群的意思.Elasticsearch集群由一个或多个节点组成,可通过其集群名称进行标识.通常这个Cluster 的名字是可以在 ...
- MongoDB 的用户和角色权限
副本和分片集群的安全设置参考这个:高级:https://files.cnblogs.com/files/sanduzxcvbnm/mongodb_advance.pdf 默认情况下,MongoDB实例 ...
- DeepHyperX代码理解-HamidaEtAl
代码复现自论文<3-D Deep Learning Approach for Remote Sensing Image Classification> 先对部分基础知识做一些整理: 一.局 ...
- Node.js(六)MongoDB
student.js var express = require('express'); var router = express.Router(); const _=require("lo ...
- 洛谷P4304 TJOI2013 攻击装置 (二分图匹配)
题目大意:一个矩阵,一些点被拿掉,在棋盘上马走日,马之间不能落在同一点,求最多放几匹马. 采用对矩阵黑白染色,画个图可以发现:马可以走到的位置和他所处的位置颜色不同,将马和他可以走到的位置连边,最多可 ...
- 洛谷P3810 陌上花开 (cdq)
最近才学了cdq,所以用cdq写的代码(这道题也是cdq的模板题) 这道题是个三维偏序问题,先对第一维排序,然后去掉重复的,然后cdq分治即可. 为什么要去掉重复的呢?因为相同的元素互相之间都能贡献, ...
- 关于从Ecplise导入项目到MyEclipse会出现冲突的原因。
昨天,从网上下了一个Eclipse的小项目导入到MyEclipse中,出现了许多错误. 原因如下. JDK的编译版本和JRE的运行版本不一致导致了这个问题. 在MyEclipse中,对项目进行Buil ...
- AlphaTensor论文阅读分析
AlphaTensor论文阅读分析 目前只是大概了解了AlphaTensor的思路和效果,完善ing deepmind博客在 https://www.deepmind.com/blog/discove ...
- CCS 2022 极客少年挑战赛 writeup
目录 题目一DSDS 操作内容: 题目二 easy_re 操作内容: flag值: 题目三 1+1=all 解题过程 题目一DSDS 操作内容: 开环境然后进入网址在网址后./目录 进入目录得到个 ...