无法使用 urllib3 发出请求

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

任何人都可以提供一个有效的 urllib3 示例吗?我已经尝试过网站上的示例https://pypi.org/project/urllib3/:

import urllib3
resp = urllib3.request("GET", "http://httpbin.org/robots.txt")

但继续收到此错误(使用 Python 3.10):

AttributeError: module 'urllib3.request' has no attribute 'Request'
python python-requests urllib3
1个回答
0
投票

使用urllib3发送HTTP请求的正确方式略有不同

import urllib3

# Create a PoolManager instance
http = urllib3.PoolManager()

# Send a GET request to http://httpbin.org/robots.txt
response = http.request("GET", "http://httpbin.org/robots.txt")


print("Status code:", response.status)
print("Response data:")
print(response.data.decode("utf-8"))  # Decode response data as UTF-8 and print

如果您尚未安装

urllib3
,请务必运行
pip install urllib3

此代码应该可以正常运行,并从

robots.txt
检索
http://httpbin.org/robots.txt
文件。

参考:https://urllib3.readthedocs.io/en/stable/user-guide.html

© www.soinside.com 2019 - 2024. All rights reserved.