当前位置: 首页 > news >正文

网络爬虫学习之httpx的使用

开篇

本文整理自《Python3 网络爬虫实战》,主要是httpx的使用。

笔记整理

使用urllib库requests库的使用,已经可以爬取绝大多数网站的数据,但对于某些网站依然无能为力。
这是因为这些网站强制使用HTTP/2.0协议访问,这时urllib和requests是无法爬取数据的,因为它们只支持HTTP/1.1,不支持HTTP/2.0。

安装

  • 使用下面命令安装httpx
 pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package httpx[http2]

基本使用

get

import httpx# 定义重试次数
retry_count = 3
for i in range(retry_count):try:# 设置超时时间为 10 秒response = httpx.get('https://www.httpbin.org/get', timeout=10)print(response.status_code)print(response.headers)print(response.text)breakexcept httpx.RequestError as e:print(f"请求失败,第 {i + 1} 次重试,错误信息: {e}")
else:print("多次重试后仍然失败,请检查网络或服务器状态。")

在这里插入图片描述
如果想要开启对HTTP/2.0的支持,需要手动声明一下:

import httpxclient = httpx.Client(http2=True) 
response = client.get('https://spa16.scrape.center/')
print(response.text)

在这里插入图片描述

其他

上面实现的是GET请求,对于POST请求、PUT请求和DELETE请求来说,实现方式是类似的:

import httpxr = httpx.get('https://www.httpbin.org/get',params={'name': 'germey'})
r = httpx.post('https://www.httpbin.org/post',data={'name': 'germey'})
r = httpx.put('https://www.httpbin.org/put')
r = httpx.delete('https://www.httpbin.org/delete')
r = httpx.patch('https://www.httpbin.org/patch')

Client对象

httpx中的Client对象,可以和requests中的Session对象类比学习。
官方比较推荐的是with as 语句,示例如下:

import httpxwith httpx.Client() as client:response = client.get('https://www.httpbin.org/get')print(response)

这个用法等同于下面这种:

import httpxclient = httpx.Client()
try:response = client.get('https://www.httpbin.org/get')print(response)
finally:client.close()

另外,在声明Client对象时可以指定一些参数,例如headers,这样使用该对象发起的所有请求都会默认带上这些参数配置:

import httpxurl = 'https://www.httpbin.org/headers'
headers = {'User-Agent': 'my-app/0.0.1'}
with httpx.Client(headers=headers) as client:response = client.get(url)print(response.json()['headers']['User-Agent'])

在这里插入图片描述

支持HTTP/2.0

要想开启对HTTP/2.0的支持,需要将http2设置为true

import httpxclient = httpx.Client(http2=True)
response = client.get('https://www.httpbin.org/get')
print(response.text)
print(response.http_version)

在这里插入图片描述

支持异步请求

import httpx
import asyncioasync def fetch(url):async with httpx.AsyncClient(http2=True) as client:response = await client.get(url)print(response.text)if __name__ == '__main__':asyncio.get_event_loop().run_until_complete(fetch('https://www.httpbin.org/get'))

在这里插入图片描述

以上便是本篇笔记的所有整理,希望对您能有所帮助~
感谢阅读!

相关文章:

  • 增强 HTNN 服务网格功能:基于 Istio 的BasicAuth 与 ACL 插件开发实战
  • 【js】JavaScript的变量提升、函数声明提升
  • 知识图谱系列(2):知识图谱的技术架构与组成要素
  • 【补充笔记】修复“NameError: name ‘ZhNormalizer‘ is not defined”的直接方法
  • Kafka如何实现高性能
  • Unity碰撞检测:射线与胶囊体投射/Layer(层)、LayerMask(遮罩层)
  • Unity3D开发AI桌面精灵/宠物系列 【六】 人物模型 语音口型同步 LipSync 、梅尔频谱MFCC技术、支持中英文自定义编辑- 基于 C# 语言开发
  • Linux云计算训练营笔记day08(MySQL数据库)
  • 【上位机——WPF】Window标签常用属性
  • 【学习心得】2025年Docker Desktop安装记录
  • 阿里云ECS部署Dify
  • 阿里云CMH镜像迁移与SMC整机迁移对比及功能详解(同地域跨主体账号场景)
  • 配置VScodePython环境Python was not found;
  • 「Java EE开发指南」如何使用MyEclipse的可视化JSF编辑器设计JSP?(二)
  • PC:使用WinSCP密钥文件连接sftp服务器
  • ANTsPy:医学影像处理python库
  • Java集合详解:LinkedBlockingQueue
  • 26考研 | 王道 | 计算机组成原理 | 一、计算机系统概述
  • Window下Jmeter多机压测方法
  • 128.在 Vue 3 中使用 OpenLayers 实现绘制矩形截图并保存地图区域
  • 明查| 新一代AI诊疗系统可3秒筛查13种癌症?没有证据
  • 江西贵溪:铜板上雕出的国潮美学
  • 人民日报任平:从汽车产销、外贸大盘看中国经济前景
  • 反制美国钢铝关税!印度拟对美国部分商品征收关税
  • 香港根据《维护国家安全条例》订立附属法例
  • 农林生物安全全国重点实验室启动建设,聚焦重大有害生物防控等