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

相关文章

Pandas使用SQLite3实战

《Pandas使用SQLite3实战》本文主要介绍了Pandas使用SQLite3实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1 环境准备2 从 SQLite3VlfrWQzgt 读取数据到 DataFrame基础用法:读

macOS无效Launchpad图标轻松删除的4 种实用方法

《macOS无效Launchpad图标轻松删除的4种实用方法》mac中不在appstore上下载的应用经常在删除后它的图标还残留在launchpad中,并且长按图标也不会出现删除符号,下面解决这个问... 在 MACOS 上,Launchpad(也就是「启动台」)是一个便捷的 App 启动工具。但有时候,应

JSON Web Token在登陆中的使用过程

《JSONWebToken在登陆中的使用过程》:本文主要介绍JSONWebToken在登陆中的使用过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录JWT 介绍微服务架构中的 JWT 使用结合微服务网关的 JWT 验证1. 用户登录,生成 JWT2. 自定义过滤

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

springboot security使用jwt认证方式

《springbootsecurity使用jwt认证方式》:本文主要介绍springbootsecurity使用jwt认证方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录前言代码示例依赖定义mapper定义用户信息的实体beansecurity相关的类提供登录接口测试提供一

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.