如何在Python中使用urllib3查看HTTP头、响应代码和html内容?

问题描述 投票:0回答:2

我有兴趣使用 urllib3 检索响应代码、正文和 HTTP 标头。我之前编写的代码是用 Python 2 编写的,现在我必须为 Python 3 重写它。

import urllib3

http = urllib3.PoolManager();
response = http.request('GET', 'http://192.168.43.131:8000')
print(response)

我尝试了不同的来源,但有人能给我指出正确的方向吗?

python urllib urllib3
2个回答
2
投票

我想你的意思是这样的:

import json

import urllib3

http = urllib3.PoolManager()
response = http.request('GET', 'http://192.168.43.131:8000')
print(response.status)
print(response.headers)
print(json.loads(response.data.decode('utf-8'))) # body

使用 或json获取正文:

import orjson  # pip install orjson
import urllib3

response = http.request('GET', 'http://192.168.43.131:8000')

print(orjson.loads(response.data)) # body

文档:https://urllib3.readthedocs.io/en/latest/user-guide.html


0
投票

我想你已经找到这个了吗?

https://urllib3.readthedocs.io/en/latest/user-guide.html#response-content

这表明您可以获取状态代码,例如,使用

print(response.status)
© www.soinside.com 2019 - 2024. All rights reserved.