python中httpx库的详细使用方法及案例详解

 更新时间:2025年02月27日 09:38:54   作者:数据知道  
httpx 是一个现代化的 Python HTTP 客户端库,支持同步和异步请求,功能强大且易于使用,它比 requests 更高效,支持 HTTP/2 和异步操作,以下是 httpx 的详细使用方法,感兴趣的小伙伴跟着小编一起来看看吧

1. 安装 httpx

首先,确保已经安装了 httpx。可以通过以下命令安装:pip install httpx

如果需要支持 HTTP/2,可以安装额外依赖:pip install httpx[http2]

2. 同步请求

发送 GET 请求

import httpx

# 发送 GET 请求
response = httpx.get('https://httpbin.org/get')
print(response.status_code)  # 状态码
print(response.text)         # 响应内容

发送 POST 请求

# 发送 POST 请求
data = {'key': 'value'}
response = httpx.post('https://httpbin.org/post', json=data)
print(response.json())  # 解析 JSON 响应

设置请求头

headers = {'User-Agent': 'my-app/1.0.0'}
response = httpx.get('https://httpbin.org/headers', headers=headers)
print(response.json())

设置查询参数

params = {'key1': 'value1', 'key2': 'value2'}
response = httpx.get('https://httpbin.org/get', params=params)
print(response.json())

处理超时

try:
    response = httpx.get('https://httpbin.org/delay/5', timeout=2.0)
except httpx.TimeoutException:
    print("请求超时")

3. 异步请求

httpx 支持异步操作,适合高性能场景。

发送异步 GET 请求

import httpx
import asyncio

async def fetch(url):
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        print(response.text)

asyncio.run(fetch('https://httpbin.org/get'))

发送异步 POST 请求

async def post_data(url, data):
    async with httpx.AsyncClient() as client:
        response = await client.post(url, json=data)
        print(response.json())

asyncio.run(post_data('https://httpbin.org/post', {'key': 'value'}))

并发请求

async def fetch_multiple(urls):
    async with httpx.AsyncClient() as client:
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks)
        for response in responses:
            print(response.text)

urls = ['https://httpbin.org/get', 'https://httpbin.org/ip']
asyncio.run(fetch_multiple(urls))

4. 高级功能

使用 HTTP/2

# 启用 HTTP/2
client = httpx.Client(http2=True)
response = client.get('https://httpbin.org/get')
print(response.http_version)  # 输出协议版本

文件上传

files = {'file': open('example.txt', 'rb')}
response = httpx.post('https://httpbin.org/post', files=files)
print(response.json())

流式请求

# 流式上传
def generate_data():
    yield b"part1"
    yield b"part2"

response = httpx.post('https://httpbin.org/post', data=generate_data())
print(response.json())

流式响应

# 流式下载
with httpx.stream('GET', 'https://httpbin.org/stream/10') as response:
    for chunk in response.iter_bytes():
        print(chunk)

5. 错误处理

httpx 提供了多种异常类,方便处理错误。

处理网络错误

try:
    response = httpx.get('https://nonexistent-domain.com')
except httpx.NetworkError:
    print("网络错误")

处理 HTTP 错误状态码

response = httpx.get('https://httpbin.org/status/404')
if response.status_code == 404:
    print("页面未找到")

6. 配置客户端

可以通过 httpx.Client 或 httpx.AsyncClient 配置全局设置。

设置超时

client = httpx.Client(timeout=10.0)
response = client.get('https://httpbin.org/get')
print(response.text)

设置代理

proxies = {
    "http://": "http://proxy.example.com:8080",
    "https://": "http://proxy.example.com:8080",
}
client = httpx.Client(proxies=proxies)
response = client.get('https://httpbin.org/get')
print(response.text)

设置基础 URL

client = httpx.Client(base_url='https://httpbin.org')
response = client.get('/get')
print(response.text)

7. 结合 Beautiful Soup 使用

httpx 可以与 Beautiful Soup 结合使用,抓取并解析网页。

import httpx
from bs4 import BeautifulSoup

# 抓取网页
response = httpx.get('https://example.com')
html = response.text

# 解析网页
soup = BeautifulSoup(html, 'lxml')
title = soup.find('title').text
print("网页标题:", title)

8. 示例:抓取并解析网页

以下是一个完整的示例,展示如何使用 httpx 抓取并解析网页数据:

import httpx
from bs4 import BeautifulSoup

# 抓取网页
url = 'https://example.com'
response = httpx.get(url)
html = response.text

# 解析网页
soup = BeautifulSoup(html, 'lxml')

# 提取标题
title = soup.find('title').text
print("网页标题:", title)

# 提取所有链接
links = soup.find_all('a', href=True)
for link in links:
    href = link['href']
    text = link.text
    print(f"链接文本: {text}, 链接地址: {href}")

9. 注意事项

性能:httpx 的异步模式适合高并发场景。

兼容性:httpx 的 API 与 requests 高度兼容,迁移成本低。

HTTP/2:如果需要使用 HTTP/2,确保安装了 httpx[http2]。

通过以上方法,可以使用 httpx 高效地发送 HTTP 请求,并结合其他工具(如 Beautiful Soup)实现数据抓取和解析。

到此这篇关于python中httpx库的详细使用方法及案例详解的文章就介绍到这了,更多相关python httpx库使用及案例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • win10 64bit下python NLTK安装教程

    win10 64bit下python NLTK安装教程

    这篇文章主要为大家详细介绍了win10 64bit下python NLTK安装教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-09-09
  • Python的可迭代对象与不可迭代对象详解

    Python的可迭代对象与不可迭代对象详解

    Python中可迭代对象需实现__iter__或__getitem__,如列表、字符串、字典等;不可迭代对象如整数、浮点数等,可用iter()或isinstance()判断,迭代器需实现__next__,可由可迭代对象转换
    2025-07-07
  • Python爬虫请求模块Urllib及Requests库安装使用教程

    Python爬虫请求模块Urllib及Requests库安装使用教程

    requests和urllib都是Python中常用的HTTP请求库,使用时需要根据实际情况选择,如果要求使用简单、功能完善、性能高的HTTP请求库,可以选择requests,如果需要兼容性更好、功能更加灵活的HTTP请求库,可以选择urllib
    2023-11-11
  • Python中命令行参数argparse模块的使用

    Python中命令行参数argparse模块的使用

    argparse是python自带的命令行参数解析包,可以用来方便的服务命令行参数。本文将通过示例和大家详细讲讲argparse的使用,需要的可以参考一下
    2023-02-02
  • Django框架安装方法图文详解

    Django框架安装方法图文详解

    这篇文章主要介绍了Django框架安装方法,结合图文与实例形式详细分析了Django框架的下载、安装简单使用方法及相关操作注意事项,需要的朋友可以参考下
    2019-11-11
  • Python发送邮件功能示例【使用QQ邮箱】

    Python发送邮件功能示例【使用QQ邮箱】

    这篇文章主要介绍了Python发送邮件功能,结合实例形式分析了Python使用QQ邮箱进行邮件发送的相关设置与使用技巧,需要的朋友可以参考下
    2018-12-12
  • Python绘制三维填充折线图的示例代码

    Python绘制三维填充折线图的示例代码

    在数据可视化领域,三维图形能够以更直观的方式展示数据之间的复杂关系,本文将为大家详细介绍如何使用Python绘制三维填充折线图,需要的小伙伴可以了解下
    2025-07-07
  • python使用ddt过程中遇到的问题及解决方案【推荐】

    python使用ddt过程中遇到的问题及解决方案【推荐】

    在使用DDT数据驱动+HTMLTestRunner输出测试报告时遇到过2个问题,没个问题都很奇葩,下面小编通过本文给大家分享python使用ddt过程中遇到的问题及解决方案,需要的朋友参考下吧
    2018-10-10
  • Python fire模块(最简化命令行生成工具)的使用教程详解

    Python fire模块(最简化命令行生成工具)的使用教程详解

    Python Fire是谷歌开源的一个第三方库,用于从任何Python对象自动生成命令行接口(CLI),可用于如快速拓展成命令行等形式。本文将通过实例为大家详细说说fire模块的使用,感兴趣的可以了解一下
    2022-10-10
  • PyQt5 加载图片和文本文件的实例

    PyQt5 加载图片和文本文件的实例

    今天小编就为大家分享一篇PyQt5 加载图片和文本文件的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06

最新评论