python - Python 3.5.1 中requests模块如何获取URL的IP地址

标签 python python-requests

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/

相关文章:

python - 使用来自 2 个数据集的数据绘制多个图形

python - 基于输入参数模拟python函数

python - python能够在多核上运行吗?

python - 如何检查请求中的 URL 是否可下载

python - 如何使用 json 将编码音频字符串传递给字节?

Python 请求有时会卡住

python - 如何找到 SSL 证书文件的路径?

python - 根据多个条件获取 df 的分段

python - pip install mysqlclient 返回 "fatal error C1083: Cannot open file: ' mysql.h' : No such file or directory

python - 如何使用具有多个参数的函数运行多处理 python 请求