Python aiohttp 需要 http/2 支持,怎么办?

最近写一个爬虫程序,一直用 aiohttp 用的好好的,突然有一天模拟登陆不正常了 查了半天发现是网站换了 http2,所有 http1.1 协议的操作请求都 403 了. 找了半天才发现现在 python 的库基本没什么支持 http2 的,就一个 hyper 可以在 client 端发送 http2 请求. 可这货也是很久不更新了,很多功能不支持,连在 https 上 proxy 都不支持,而且功能少的可怜,很难用. 现在我想请教一下各位,有没有什么好的办法


Python aiohttp 需要 http/2 支持,怎么办?

9 回复

思路是,http2 应该有降级模式,不可能只强制使用 http2 协议连接,或许能解决你的问题。


要在 aiohttp 中使用 HTTP/2,你需要安装支持 HTTP/2 的依赖库 aiohttp[h2]aiohttp[http2]

首先,用 pip 安装:

pip install 'aiohttp[h2]'
# 或者
pip install 'aiohttp[http2]'

然后在创建 aiohttp.ClientSession 时启用 HTTP/2:

import aiohttp
import asyncio

async def main():
    connector = aiohttp.TCPConnector(force_close=True, enable_cleanup_closed=True)
    
    async with aiohttp.ClientSession(
        connector=connector,
        timeout=aiohttp.ClientTimeout(total=30)
    ) as session:
        # 发送请求时会自动协商使用 HTTP/2
        async with session.get('https://http2.pro/api/v1') as response:
            print(f'HTTP/{response.version.major}')  # 应该输出 2
            print(await response.text())

if __name__ == '__main__':
    asyncio.run(main())

几点说明:

  1. 服务端必须支持 HTTP/2,客户端才能使用
  2. 默认会优先尝试 HTTP/2,如果不支持则回退到 HTTP/1.1
  3. 可以通过 response.version 查看实际使用的协议版本

如果遇到问题,检查一下 OpenSSL 版本是否足够新(建议 1.1.1+)。

总结:装 aiohttp[h2] 包,创建 session 时用默认配置就行。

换 go

requests 手动导入证书就行了 aiohttp 应该也可以的

网页页面 http1.1 可以请求打开查看,但是所有的 API 操作请求,都强制 http2 了.

证书和 http 协议版本有关系吗

#5
https://docs.aiohttp.org/en/stable/client_advanced.html#ssl-control-for-tcp-sockets
看这里,默认是没有导入证书的所以不支持 https 手动指定一个证书就行了

现在不是 https 的问题,是被爬的网站必须使用 http/2 协议才能正常模拟登陆操作. 但是 aiohttp 现在还不支持 http/2 协议

诶,这个站用不支持 h2 的浏览器不会降级么?

回到顶部