python 仅请求流迭代标头而不是主体

问题描述 投票:0回答:1

这个代码是我从这个网站

获得的
import requests
req = requests.get('path/to/forest.jpg', stream=True)
req.raise_for_status()
with open('Forest.jpg', 'wb') as fd:
  for chunk in req.iter_content(chunk_size=50000):
    print('Received a Chunk')
    fd.write(chunk)

基本上,该代码解释了如何流畅地获取正文内容。我的情况也类似。我只想迭代 http header,而不是迭代正文内容。具体来说,我只想获取

Set-Cookie
标头,然后终止连接。通过这样做,如果正文内容很大而我只需要标题,我可以节省下载带宽。

python request stream
1个回答
0
投票

如果我理解正确的话,你可以使用

response.headers
仅获取 HTTP 标头:

import requests

resp = requests.get("https://www.google.com", stream=True)
print(resp.headers["Set-Cookie"])

打印:

SOCS=ABBaBgiFrKdpBg; expires=Tue, 12-Nov-2024 10:43:27 GMT; path=/; domain=.google.com; ...
© www.soinside.com 2019 - 2024. All rights reserved.