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/ 前言 很多朋友对异步编程都处于"听说很强大"的认知状态.鲜有在生产项目中使用它.而使用它的同学,则大多数都停留在知 ...
随机推荐
- Elastic:使用ElastAlert发送通知
ElastAlert是一个简单的框架,用于从Elasticsearch中的数据中发出异常,尖峰或其他感兴趣模式的警报.我们可以在地址https://elastalert.readthedocs.io/ ...
- 第六章:Django 综合篇 - 4:django-admin和manage.py
目录 一.Django内置命令选项 check dbshell diffsettings flush makemigrations migrate runserver shell startapp s ...
- P7476 苦涩 题解
Link 一道很好的复杂度均摊题目. 只需要考虑删除操作时的时间复杂度.保证复杂度的重点之一是精确定位到所有包含最大值的区间,即不去碰多余的区间.每次删除操作会删除若干个整个区间,以及至多两个区间被删 ...
- 原生js的懒人轮播图
<style> body{ margin: 0; padding: 0px;}#carousel{ margin: auto; /* 居中 */ width: 600px; /* 设置宽度 ...
- 【C++】从零开始的CS:GO逆向分析3——写出一个透视
[C++]从零开始的CS:GO逆向分析3--写出一个透视 本篇内容包括: 1. 透视实现的方法介绍 2. 通过进程名获取进程id和进程句柄 3. 通过进程id获取进程中的模块信息(模块大小,模块地址, ...
- Kafka与Flume之集成比较
Kafka与Flume之集成比较 一.Kafka与Flume比较 在企业中必须要清楚流式数据采集框架flume和kafka的定位是什么:flume:cloudera公司研发: 适合多个生产者: 适合下 ...
- 小程序 wx.navigateTo和 wx.redirectTo区别
wx.navigateTo 官方解释: 意思就是说. A页面跳转B页面 B页面做了操作,点击保存,再跳转回A页面 此时,如果点击左上返回按钮,仍然可以跳转回B页面,而且里面的数据是操作之前的数据 wx ...
- Dubbo 原理和机制详解 (非常全面)
Dubbo 是一款Java RPC框架,致力于提供高性能的 RPC 远程服务调用方案.作为主流的微服务框架之一,Dubbo 为开发人员带来了非常多的便利. 大家好,我是 mikechen,专注分享「互 ...
- NLP之Bi-LSTM(在长句中预测下一个单词)
Bi-LSTM @ 目录 Bi-LSTM 1.理论 1.1 基本模型 1.2 Bi-LSTM的特点 2.实验 2.1 实验步骤 2.2 实验模型 1.理论 1.1 基本模型 Bi-LSTM模型分为2个 ...
- 题解 UVA439 骑士的移动 Knight Moves
前言 最近板子题刷多了-- 题意 一个 \(8\times 8\) 的棋盘,问马从起点到终点的最短步数为多少. \(\sf Solution\) 要求最短路径嘛,显然 bfs 更优. 读入 这个读入处 ...