该代码示例展示了如何在Python中使用aiohttp库进行异步Post请求,包括设置headers、数据和代理。同时,它还包含了一个Get请求的简要说明,强调了参数传递和重定向处理。
摘要生成于
,由 DeepSeek-R1 满血版支持,
class
Win
:
async
def
post_request
(
self
,
session
,
t
)
:
await
asyncio
.
sleep
(
0.3
)
print
(
t
)
url
=
'https://ug.baidu.com/mcp/pc/pcsearch'
data
=
{
"invoke_info"
:
{
"pos_1"
:
[
{
}
]
,
"pos_2"
:
[
{
}
]
,
"pos_3"
:
[
{
}
]
}
}
headers
=
{
'User-Agent'
:
'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
,
proxy
=
None
try
:
async
with
session
.
post
(
url
=
url
,
headers
=
headers
,
data
=
json
.
dumps
(
data
)
,
proxy
=
proxy
)
as
response
:
if
response
.
status
==
200
:
text
=
await
response
.
text
(
)
print
(
"Success"
,
text
)
except
aiohttp
.
ClientError
as
e
:
print
(
"Error:"
,
e
)
async
def
run
(
self
,
t
)
:
async
with
aiohttp
.
ClientSession
(
)
as
session
:
tasks
=
[
]
for
i
in
range
(
1
)
:
task
=
asyncio
.
ensure_future
(
self
.
post_request
(
session
,
t
)
)
tasks
.
append
(
task
)
await
asyncio
.
gather
(
*
tasks
)
def
main
(
self
)
:
loop
=
asyncio
.
get_event_loop
(
)
t
=
time
.
time
(
)
loop
.
run_until_complete
(
self
.
run
(
t
)
)
print
(
time
.
time
(
)
-
t
)
if
__name__
==
"__main__"
:
a
=
Win
(
)
a
.
main
(
)
二、Get请求
类似于requests的get,使用和上面差不多(params,allow_redirects都能用),代理使用参考上面post请求用proxy。
需要指出的是,
爬虫
里面的requests是一个不支持
异步
的模块,而需要用到
异步
爬虫
的话,可以使用
aiohttp
+
asyncio
的方法。
import
asyncio
import time
import
aiohttp
from lxml import etree
# 假设将目标网站放入到待爬取的列表中
urls = ['https://www.qiushibaike.com/',
'https://www.qiushibaike.com/8hr/page/2/']
# asyn
asyncio
是遵循
Python
标准
库
的一个
异步
I/O框架.在这篇文章里,我将介绍uvloop: 可以完整替代
asyncio
事件循环.uvloop是用Cython写的,基于libuv.
uvloop 使得
asyncio
更快. 实际上,比nodejs,gevent,以及其他任何
Python
异步
框架至少快两倍.uvloop
asyncio
基于性能的测试接近于Go程序.
python
相关学习资料:https://edu.51cto.com/video/1158.htmlhttps://edu.51cto.com/video/4102.htmlhttps://edu.51cto.com/video/3832.html
Python
异步
POST
请求
入门指南
作为一名经验丰富的
开发
者,...