网络爬虫学习之httpx的使用

开篇

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

笔记整理

使用urllib库requests库的使用,已经可以爬取绝大多数网站的数据,但对于某些网站依然无能为力。

这是因为这些网站强制使用HTTP/2.0协议访问,这时urllib和requests是无法爬取数据的,因为它们只支持HTTP/1.1,不支持HTTP/2.0。

安装

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

基本使用

get

c 复制代码
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)
        break
    except httpx.RequestError as e:
        print(f"请求失败,第 {i + 1} 次重试,错误信息: {e}")
else:
    print("多次重试后仍然失败,请检查网络或服务器状态。")

如果想要开启对HTTP/2.0的支持,需要手动声明一下:

c 复制代码
import httpx

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

其他

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

c 复制代码
import httpx

r = 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 语句,示例如下:

c 复制代码
import httpx

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

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

c 复制代码
import httpx

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

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

c 复制代码
import httpx

url = '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

c 复制代码
import httpx

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

支持异步请求

c 复制代码
import httpx
import asyncio

async 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'))

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

感谢阅读!

相关推荐
2601_962299243 小时前
Azure python操作系统列表
python·操作系统·azure·虚拟机·存储配置文件
学术 学术 Fun4 小时前
如何用 API 与 Webhook 批量把图表图片转换成 VSDX
python·自动化·api·visio
2601_962100545 小时前
python包和模块的内容整理
python·模块·导入·虚拟环境·
二进制漫游记5 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
-今昭-6 小时前
《V2V 迁移实战:将 VMware 虚拟机转为 OpenStack 可用 Glance qcow2 镜像》
开发语言·python
2601_962381586 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全
用户3721574261356 小时前
如何使用 Python 从 Word 文档中提取图片
python
白山编程大哥8 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
绘梨衣5479 小时前
AI技术栈全景指南_Prompt_RAG_爬虫_MCP
人工智能·爬虫·prompt
昭昭日月明9 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程