Python请求:缺少内容长度响应

时间:2020-05-24 19:14:30

标签: python python-3.x get python-requests head

Python请求不会返回curl所能获得的content-length标头。

def get_headers(url):
    response = requests.head(url)
    return response.headers

响应:

{'Server': 'nginx/1.17.9', 'Date': 'Sun, 24 May 2020 19:09:02 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding', 'Access-Control-Allow-Origin': '*', 'Content-Disposition': 'inline; filename="introduction - Sia API Documentation.html"', 'Skynet-File-Metadata': '{"filename":"introduction - Sia API Documentation.html"}', 'Access-Control-Expose-Headers': 'skynet-file-metadata', 'Content-Encoding': 'gzip'}

我也尝试了request.get,但也无法正常工作: response = requests.get(url, stream=True)

1 个答案:

答案 0 :(得分:0)

如果您查看返回的标题,您会发现:

Transfer-Encoding: chunked

如果比较使用httpbin发送的标头,则可能会注意到请求也发送了Accept-Encoding:gzip,deflate。如果您删除该标头,例如

r = requests.head(url, headers={'Accept-Encoding': None})

然后您将获得Content-Length标头。

来源:https://github.com/psf/requests/issues/3953