Python HTTPX 基础用法

896 阅读1分钟

引入

HTTPX是Python3的功能齐全的HTTP客户端,它提供同步和异步API。

和大名鼎鼎的requests相比,HTTPX常用于发送异步请求。

在此记录基础用法,方便查阅。

使用

同步请求

基本等同于 requests

1. 简单请求

requests一致

import httpx
res = httpx.get('https://httpbin.org/get')
res = httpx.post('https://httpbin.org/post', data={'key': 'value'}, headers={'ua':'test'})
res = httpx.post('https://httpbin.org/post', cookies={'test':'testVal'})

# 获取cookies字典的方法
cookies = {cookie.name: cookie.value for cookie in res.cookies.jar}
# 若已知键
val = res.cookies['test']

# 获取请求头等等类似
headers = {k: v for k,v in res.headers.items()}

2.使用Client

使用httpx.Client代替requests.Session

# 使用with
with httpx.Client() as client:
    res = client.get('https://httpbin.org/get')

# 同样的可以初始化请求头等信息,若client.get()中附带了新的请求头,两者会合并(优先使用get中的)
client = httpx.Client(headers={'ua':'test'})
try:
    res = client.get('https://httpbin.org/get')
finally:
    # close()明确关闭连接池
    client.close()

修改Client中的请求头等

client.headers.update({'ua':'test2', 'foo':'bar'})

异步请求

仅仅举例,具体用法和同步类似

import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://example.org/')