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

时间:2016-11-21 15:43:19

标签: python request http-headers python-requests response

我正在使用Python编写一个管理器,在某些情况下会下载一些文件。问题是要对响应头执行条件。

以下示例是我现在所做的简化版本。我首先下载该文件,然后测试它包含在标题中的名称是否在先前定义的列表中。

我想知道是否有办法在不下载内容的情况下获得响应,这在我的实际案例中需要花费大量时间。

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

1 个答案:

答案 0 :(得分:9)

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

相关问题