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'
可能是某些版本问题。请帮忙。
P.S。无法在原帖中发表评论。
答案 0 :(得分:5)
你到了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())