python - 有没有办法在不下载 Python 中的 url 内容的情况下获取响应 header ?

标签 python request http-headers python-requests response

<分区>

我正在使用 Python 编写一个管理器,该管理器将在给定条件的情况下下载一些文件。问题是要针对响应 header 执行条件。

下面的示例是我现在正在做的事情的简化版本。我首先下载该文件,然后测试它的名称(包含在 header 中)是否在之前定义的列表中。

我想知道是否有一种方法可以在不下载内容的情况下获得响应,在我的实际情况下这会花费大量时间。

import requests

# The line below download the file, but I'd like not to do it.
req = requests.get('http://some_url.com/some_file')

# Get the name of the file to test if it's the right file.
r = re.search(r'filename="(.*)";', req.headers['Content-Disposition'])

filename = None

# If the filename is present in the headers...
if r.groups():
    filename = r.groups()[0]

# If the filename is in an authorized list...
if filename in [...]:
   # Process req.content

最佳答案

您可以使用 requests.head() 代替 requests.get()

关于python - 有没有办法在不下载 Python 中的 url 内容的情况下获取响应 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723992/

相关文章:

python - 如何改进我的数据集以增加 yolov4 对象检测框架中的 mAP

python - 如何更快地一次绘制数千个圆 openCv - (也许使用 GPU)

Python 字符串格式 - 限制字符串长度,但修剪字符串开头

javascript - 修改 Geonames 的 JSON Ajax 请求

asp.net - IIS 301 重定向 - 将原始 URL 通知最终站点的任何方式

java - 如何从 java 中的 HttpHeaders 对象中查找客户端 ip 地址?

python - Plotly-Dash : Want two stacked bar charts side by side from single df column

java - 在 HttpSessionListener 中如何获取 HttpServletRequest?

php - 如何使用 Apache 禁用 Content-Length 响应 header ?

http-headers - 什么是内容语言和接受语言?