aiohttp的异步爬虫使用方法

2024-01-21 03:48

本文主要是介绍aiohttp的异步爬虫使用方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

aiohttp是python3的一个异步模块,分为服务器端和客户端。廖雪峰的python3教程中,讲的是服务器端的使用方法。均益这里主要讲的是客户端的方法,用来写爬虫。使用异步协程的方式写爬虫,能提高程序的运行效率。

1、安装

Python
pip install <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/aiohttp" title="View all posts in aiohttp" target="_blank">aiohttp</a></span>
1
2
pip install aiohttp

2、单一请求方法

Python
import aiohttp import asyncio async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(url): async with aiohttp.ClientSession() as session: html = await fetch(session, url) print(html) url = 'http://junyiseo.com' loop = asyncio.get_event_loop() loop.run_until_complete(main(url))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import aiohttp
import asyncio
async def fetch ( session , url ) :
async with session . get ( url ) as response :
return await response . text ( )
async def main ( url ) :
async with aiohttp . ClientSession ( ) as session :
html = await fetch ( session , url )
print ( html )
url = 'http://junyiseo.com'
loop = asyncio . get_event_loop ( )
loop . run_until_complete ( main ( url ) )

3、多url请求方法

Python
import aiohttp import asyncio async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(url): async with aiohttp.ClientSession() as session: html = await fetch(session, url) print(html) loop = asyncio.get_event_loop() # 生成多个请求方法 url = "http://junyiseo.com" tasks = [main(url), main(url)] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import aiohttp
import asyncio
async def fetch ( session , url ) :
async with session . get ( url ) as response :
return await response . text ( )
async def main ( url ) :
async with aiohttp . ClientSession ( ) as session :
html = await fetch ( session , url )
print ( html )
loop = asyncio . get_event_loop ( )
# 生成多个请求方法
url = "http://junyiseo.com"
tasks = [ main ( url ) , main ( url ) ]
loop . run_until_complete ( asyncio . wait ( tasks ) )
loop . close ( )

4、其他的请求方式

上面的代码中,我们创建了一个 ClientSession 对象命名为session,然后通过session的get方法得到一个 ClientResponse 对象,命名为resp,get方法中传入了一个必须的参数url,就是要获得源码的http url。至此便通过协程完成了一个异步IO的get请求。
aiohttp也支持其他的请求方式

Python
session.post('http://httpbin.org/post', data=b'data') session.put('http://httpbin.org/put', data=b'data') session.delete('http://httpbin.org/delete') session.head('http://httpbin.org/get') session.options('http://httpbin.org/get') session.patch('http://httpbin.org/patch', data=b'data')
1
2
3
4
5
6
7
8
session . post ( 'http://httpbin.org/post' , data = b 'data' )
session . put ( 'http://httpbin.org/put' , data = b 'data' )
session . delete ( 'http://httpbin.org/delete' )
session . head ( 'http://httpbin.org/get' )
session . options ( 'http://httpbin.org/get' )
session . patch ( 'http://httpbin.org/patch' , data = b 'data' )

5、请求方法中携带参数

GET方法带参数

Python
params = {'key1': 'value1', 'key2': 'value2'} async with session.get('http://httpbin.org/get', params=params) as resp: expect = 'http://httpbin.org/get?key2=value2&key1=value1' assert str(resp.url) == expect
1
2
3
4
5
6
params = { 'key1' : 'value1' , 'key2' : 'value2' }
async with session . get ( 'http://httpbin.org/get' ,
params = params ) as resp :
expect = 'http://httpbin.org/get?key2=value2&key1=value1'
assert str ( resp . url ) == expect

POST方法带参数

Python
payload = {'key1': 'value1', 'key2': 'value2'} async with session.post('http://httpbin.org/post', data=payload) as resp: print(await resp.text())
1
2
3
4
5
payload = { 'key1' : 'value1' , 'key2' : 'value2' }
async with session . post ( 'http://httpbin.org/post' ,
data = payload ) as resp :
print ( await resp . text ( ) )

6、获取响应内容

resp.status 是http状态码,
resp.text() 是网页内容

Python
async with session.get('https://api.github.com/events') as resp: print(resp.status) print(await resp.text())
1
2
3
4
async with session . get ( 'https://api.github.com/events' ) as resp :
print ( resp . status )
print ( await resp . text ( ) )

gzip和deflate转换编码已经为你自动解码。

7、JSON请求处理

Python
async with aiohttp.ClientSession() as session: async with session.post(url, json={'test': 'object'})
1
2
3
async with aiohttp . ClientSession ( ) as session :
async with session . post ( url , json = { 'test' : 'object' } )

返回json数据的处理

Python
async with session.get('https://api.github.com/events') as resp: print(await resp.json())
1
2
3
async with session . get ( 'https://api.github.com/events' ) as resp :
print ( await resp . json ( ) )

8、以字节流的方式读取文件,可以用来下载

Python
async with session.get('https://api.github.com/events') as resp: await resp.content.read(10) #读取前10个字节
1
2
3
async with session . get ( 'https://api.github.com/events' ) as resp :
await resp . content . read ( 10 ) #读取前10个字节

下载保存文件

Python
with open(filename, 'wb') as fd: while True: chunk = await resp.content.read(chunk_size) if not chunk: break fd.write(chunk)
1
2
3
4
5
6
7
with open ( filename , 'wb' ) as fd :
while True :
chunk = await resp . content . read ( chunk_size )
if not chunk :
break
fd . write ( chunk )

9、上传文件

Python
url = 'http://httpbin.org/post' files = {'file': open('report.xls', 'rb')} await session.post(url, data=files)
1
2
3
4
5
url = 'http://httpbin.org/post'
files = { 'file' : open ( 'report.xls' , 'rb' ) }
await session . post ( url , data = files )

可以设置好文件名和content-type:

Python
url = 'http://httpbin.org/post' data = FormData() data.add_field('file', open('report.xls', 'rb'), filename='report.xls', content_type='application/vnd.ms-excel') await session.post(url, data=data)
1
2
3
4
5
6
7
8
9
url = 'http://httpbin.org/post'
data = FormData ( )
data . add_field ( 'file' ,
open ( 'report.xls' , 'rb' ) ,
filename = 'report.xls' ,
content_type = 'application/vnd.ms-excel' )
await session . post ( url , data = data )

10、超时处理

默认的IO操作都有5分钟的响应时间 我们可以通过 timeout 进行重写,如果 timeout=None 或者 timeout=0 将不进行超时检查,也就是不限时长。

Python
async with session.get('https://github.com', timeout=60) as r: ...
1
2
3
async with session . get ( 'https://github.com' , timeout = 60 ) as r :
. . .

11、自定义请求头

Python
url = 'http://example.com/image' payload = b'GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00' b'\x00\x00\x01\x00\x01\x00\x00\x02\x00;' headers = {'content-type': 'image/gif'} await session.post(url, data=payload, headers=headers)
1
2
3
4
5
6
7
8
9
url = 'http://example.com/image'
payload = b 'GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00'
b '\x00\x00\x01\x00\x01\x00\x00\x02\x00;'
headers = { 'content-type' : 'image/gif' }
await session . post ( url ,
data = payload ,
headers = headers )

设置session的请求头

Python
headers={"Authorization": "Basic bG9naW46cGFzcw=="} async with aiohttp.ClientSession(headers=headers) as session: async with session.get("http://httpbin.org/headers") as r: json_body = await r.json() assert json_body['headers']['Authorization'] == \ 'Basic bG9naW46cGFzcw=='
1
2
3
4
5
6
7
headers = { "Authorization" : "Basic bG9naW46cGFzcw==" }
async with aiohttp . ClientSession ( headers = headers ) as session :
async with session . get ( "http://httpbin.org/headers" ) as r :
json_body = await r . json ( )
assert json_body [ 'headers' ] [ 'Authorization' ] == \
'Basic bG9naW46cGFzcw=='

12、自定义cookie

Python
url = 'http://httpbin.org/cookies' cookies = {'cookies_are': 'working'} async with ClientSession(cookies=cookies) as session: async with session.get(url) as resp: assert await resp.json() == { "cookies": {"cookies_are": "working"}}
1
2
3
4
5
6
7
url = 'http://httpbin.org/cookies'
cookies = { 'cookies_are' : 'working' }
async with ClientSession ( cookies = cookies ) as session :
async with session . get ( url ) as resp :
assert await resp . json ( ) == {
"cookies" : { "cookies_are" : "working" } }

在多个请求中共享cookie

Python
async with aiohttp.ClientSession() as session: await session.get( 'http://httpbin.org/cookies/set?my_cookie=my_value') filtered = session.cookie_jar.filter_cookies( 'http://httpbin.org') assert filtered['my_cookie'].value == 'my_value' async with session.get('http://httpbin.org/cookies') as r: json_body = await r.json() assert json_body['cookies']['my_cookie'] == 'my_value'
1
2
3
4
5
6
7
8
9
10
async with aiohttp . ClientSession ( ) as session :
await session . get (
'http://httpbin.org/cookies/set?my_cookie=my_value' )
filtered = session . cookie_jar . filter_cookies (
'http://httpbin.org' )
assert filtered [ 'my_cookie' ] . value == 'my_value'
async with session . get ( 'http://httpbin.org/cookies' ) as r :
json_body = await r . json ( )
assert json_body [ 'cookies' ] [ 'my_cookie' ] == 'my_value'

13、限制同时请求数量

limit默认是100,limit=0的时候是无限制

Python
conn = aiohttp.TCPConnector(limit=30)
1
2
conn = aiohttp . TCPConnector ( limit = 30 )

14、SSL加密请求

有的请求需要验证加密证书,可以设置ssl=False,取消验证

Python
r = await session.get('https://example.com', ssl=False)
1
2
r = await session . get ( 'https://example.com' , ssl = False )

加入证书

Python
sslcontext = ssl.create_default_context( cafile='/path/to/ca-bundle.crt') r = await session.get('https://example.com', ssl=sslcontext)
1
2
3
4
sslcontext = ssl . create_default_context (
cafile = '/path/to/ca-bundle.crt' )
r = await session . get ( 'https://example.com' , ssl = sslcontext )

15、代理请求

Python
async with aiohttp.ClientSession() as session: async with session.get("http://<span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span>.org", proxy="http://proxy.com") as resp: print(resp.status)
1
2
3
4
5
async with aiohttp . ClientSession ( ) as session :
async with session . get ( "http://python.org" ,
proxy = "http://proxy.com" ) as resp :
print ( resp . status )

代理认证

Python
async with aiohttp.ClientSession() as session: proxy_auth = aiohttp.BasicAuth('user', 'pass') async with session.get("http://<span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span>.org", proxy="http://proxy.com", proxy_auth=proxy_auth) as resp: print(resp.status)
1
2
3
4
5
6
7
async with aiohttp . ClientSession ( ) as session :
proxy_auth = aiohttp . BasicAuth ( 'user' , 'pass' )
async with session . get ( "http://python.org" ,
proxy = "http://proxy.com" ,
proxy_auth = proxy_auth ) as resp :
print ( resp . status )

或者通过URL认证

Python
session.get("http://python.org", proxy="http://user:pass@some.proxy.com")
1
2
3
session . get ( "http://python.org" ,
proxy = "http://user:pass@some.proxy.com" )

16、优雅的关闭程序

没有ssl的情况,加入这个语句关闭await asyncio.sleep(0)

Python
async def read_website(): async with aiohttp.ClientSession() as session: async with session.get('http://example.org/') as resp: await resp.read() loop = asyncio.get_event_loop() loop.run_until_complete(read_website()) # Zero-sleep to allow underlying connections to close loop.run_until_complete(asyncio.sleep(0)) loop.close()
1
2
3
4
5
6
7
8
9
10
11
async def read_website ( ) :
async with aiohttp . ClientSession ( ) as session :
async with session . get ( 'http://example.org/' ) as resp :
await resp . read ( )
loop = asyncio . get_event_loop ( )
loop . run_until_complete ( read_website ( ) )
# Zero-sleep to allow underlying connections to close
loop . run_until_complete ( asyncio . sleep ( 0 ) )
loop . close ( )

如果是ssl请求,在关闭前需要等待一会

Python
loop.run_until_complete(asyncio.sleep(0.250)) loop.close()
1
2
3
loop . run_until_complete ( asyncio . sleep ( 0.250 ) )
loop . close ( )

*** 转自均益博客




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱

这篇关于aiohttp的异步爬虫使用方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/628284

相关文章

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用

flask库中sessions.py的使用小结

《flask库中sessions.py的使用小结》在Flask中Session是一种用于在不同请求之间存储用户数据的机制,Session默认是基于客户端Cookie的,但数据会经过加密签名,防止篡改,... 目录1. Flask Session 的基本使用(1) 启用 Session(2) 存储和读取 Se