Python 版本:3.5.1
请求版本:2.9.1。
我正在尝试获取 python 请求中 url 的 IP 地址,如下所示:How do I get the IP address from a http request using the requests library?
import requests
rsp = requests.get('http://google.com', stream=True)
# grab the IP while you can, before you consume the body!!!!!!!!
print (rsp.raw._fp.fp._sock.getpeername())
# consume the body, which calls the read(), after that fileno is no longer available.
print (rsp.content)
出现以下错误:
AttributeError: '_io.BufferedReader' object has no attribute '_sock'
可能是版本问题。请帮忙。
附言无法在原始帖子中发表评论。
最佳答案
您到达了 BufferedReader
instance ;它是添加缓冲区的实际文件对象的包装器。可以通过 raw
attribute 访问原始文件对象:
print(rsp.raw._fp.fp.raw._sock.getpeername())
演示:
>>> import requests
>>> rsp = requests.get('http://google.com', stream=True)
>>> print(rsp.raw._fp.fp.raw._sock.getpeername())
('2a00:1450:400b:c02::69', 80, 0, 0)
要使代码在 Python 2 和 3 上都能运行,请查看 raw
属性是否存在:
fp = rsp.raw._fp.fp
sock = fp.raw._sock if hasattr(fp, 'raw') else fp._sock
print(sock.getpeername())
关于python - Python 3.5.1 中requests模块如何获取URL的IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36357369/