这个代码是我从这个网站
获得的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
标头,然后终止连接。通过这样做,如果正文内容很大而我只需要标题,我可以节省下载带宽。
如果我理解正确的话,你可以使用
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; ...