Skip to main content
 首页 » 编程设计

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

2025年05月04日11leader

<分区>

我正在使用 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