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

网络爬虫学习之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'))

在这里插入图片描述

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

http://www.xdnf.cn/news/6486.html

相关文章:

  • 函数专题1
  • 【大模型面试每日一题】Day 19:如何设计自动化评估框架验证大模型的多步推理能力(如数学解题)?
  • 使用Python与正则表达式高效提取Excel中的票号数据
  • 2.Klipper开发篇:Klipper上位机源码分析
  • 时源芯微|TSFE0806U-2L-900TF复合共模滤波器在USB端口保护
  • Python函数参数传递机制深度解析:值传递与引用传递的真相
  • 理解c++中关键字友元friend的作用
  • 盲盒:拆开未知的惊喜,收藏生活的仪式感
  • 现代生活中的创新健康养生之道
  • LLM笔记(二)LLM数据基础
  • 【C++】Module CPP:模块化编程 Demo
  • 【C#】Thread.Join()、异步等待和直接join
  • C++delete详解剖析
  • 工具类来生成蓝牙指令
  • Java 序列化(Serialization)
  • 奇妙协同效应,EtherNet IP与PROFINET网关优化半导体生产线
  • Git .gitattributes 文件用途详解
  • Baklib知识中台驱动智能服务新实践
  • ZCC6303x-60V/1.2MHz 高效率升压 LED 恒流驱动替代SY7301
  • 【图片识别工具】批量单据识别批量重命名,批量OCR识别图片文字并重命名,批量改名工具的使用步骤和注意事项
  • Modbus TCP转Profinet网关:数字化工厂异构网络融合的核心枢纽
  • pciutils-3.5.5-win64工具的使用方法
  • Java大师成长计划之第23天:Spring生态与微服务架构之服务发现与注册中心
  • 使用命令行拉取 Git 仓库
  • 数学复习笔记 9
  • 自学嵌入式 day 18 - 数据结构 1
  • 嵌软面试每日一阅----FreeRTOS
  • SpringBoot实现简单的API代理服务器
  • Sumsub 活体检测与人证对比 Java Demo
  • pytorch训练可视化工具---TensorBoard