任何人都可以提供一个有效的 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'
使用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
文件。