关于python:python-包之-httpx-请求操作教程

37次阅读

共计 1967 个字符,预计需要花费 5 分钟才能阅读完成。

一、装置
httpx 是 Python 新一代的网络申请库
httpx 与 requests 库的根本应用办法简直是截然不同的
基于 Python3 的功能齐全的 http 申请模块
既能发送同步申请,也能发送异步申请
反对 HTTP/1.1 和 HTTP/2
反对间接向 WSGI 应用程序或者 ASGI 应用程序发送申请

pip install httpx

二、申请类型

import httpx
httpx.get('https://www.baidu.com')
httpx.post('https://www.baidu.com')
httpx.put('https://www.baidu.com')
httpx.delete('https://www.baidu.com')
httpx.head('https://www.baidu.com')
httpx.options('https://www.baidu.com')

三、带参数申请

import httpx

data = {
    'name': 'autofelix',
    'age': 25
}

response = httpx.get('https://www.baidu.com', params=data)
print(response.url)
print(response.text)

四、自定义 headers

import httpx

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
response =httpx.get('https://www.baidu.com', headers=headers)
print(response.text)

五、申请的属性

import httpx

response = httpx.get('https://www.baidu.com')

# 响应状态码
response.status_code
# 响应头
response.headers
# 响应 cookie
response.cookies
# 申请 url
response.url
# 历史记录
response.history

六、应用 client 发送申请

import httpx

with httpx.Client() as client:
    response = client.get('https://www.baidu.com')
    print(response.text)

七、HTTP 代理

import httpx

proxies= {
    'http': 'http://127.0.0.1:9999',
    'https': 'http://127.0.0.1:8888'
}

with httpx.Client(proxies=proxies) as client:
    response = client.get('https://www.baidu.com')
    print(response)

八、超时解决

import httpx

# 一般申请超时解决
httpx.get('https://www.baidu.com', timeout=10.0)

# 一般申请敞开超时解决
httpx.get('https://www.baidu.com', timeout=None)

# client 实例超时解决
with httpx.Client() as client:
    client.get('https://www.baidu.com', timeout=None)
    
# client 实例敞开超时解决
with httpx.Client() as client:
    client.get('https://www.baidu.com', timeout=10.0)

九、SSL 验证

import httpx

# 自带 ca 证书
response = httpx.get('https://www.baidu.com', verify="path/cert/client.pem")

# 齐全禁用 SSL 验证
response = httpx.get('https://www.baidu.com', verify=False)

十、异步操作
应用 async/await 语句来进行异步操作
应用异步 client 比应用多线程发送申请更加高效,更能体现显著的性能劣势

import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client: 
        response = await client.get('https://www.baidu.com')
        print(response)

if __name__ == '__main__':
    asyncio.run(main())

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注 Python 技术大本营,获取更多技能与教程。

正文完
 0