Python 请求库添加了一个附加 header "Accept-Encoding: identity"

标签 python http http-headers python-requests

这是我的代码。

import requests
from sys import exit
proxies = {
    "http": "127.0.0.1:8888",
    "https": "127.0.0.1:8888",
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0",
    "Accept-Encoding": "gzip, deflate",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
    "Connection": "keep-alive"
}


login_page = "http://www.test.com/login/"
r = requests.get(login_page, proxies = proxies, headers = headers)
original_cookies = r.cookies
exit(0)

这是我从 fiddler2 得到的。如您所见,它添加了一个额外的 header Accept-Encoding: identity

GET http://www.test.com/login/ HTTP/1.1
Accept-Encoding: identity
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Host: www.test.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0

我在 Windows 7 64 位上使用 Python 3.3.2 并请求 1.2.3。

谁能给些建议?

谢谢。

最佳答案

这起源于 http.client 的内心深处,由 urllib3 使用,由 requests 使用。

http.client 实际上checks如果传递的 headers 字典中已经有 accept-encoding,并且如果有它会跳过添加 identity header - 唯一的问题是作为 headers 字典传递的内容是这样的:

CaseInsensitiveDict({b'Accept-Encoding': 'gzip, deflate, compress', ...})

为什么它不起作用? 请求 encodes header 名称,在 python3 中,与 bytes 对象相比,str 对象始终为 False,在 http 中执行检查。客户端失败...

如果你真的想摆脱额外的标题,最快的方法是注释掉 line 340 in requests/models.py ,或 monkeypatch requests.models.PreparedRequest.prepare_headers

编辑:
这似乎是 fixed在(尚未发布的)2.0 请求分支中

关于Python 请求库添加了一个附加 header "Accept-Encoding: identity",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704429/

相关文章:

Java HttpGet 不接受 gzip

python - 有没有一种 pythonic 方法可以将标量和 0d 数组更改为 1d 数组?

python - 在 BeautifulSoup 中处理无限滚动 UI

http - Web 服务器如何确定 ETag 值是否是最新的?

node.js - express 和 http 服务器一起使用

python - 使用具有多个 header 的 urllib 发出 POST 请求会出现 400 Bad Request 错误

python - diy Tornado openshift 套接字错误

python - 将目标与 fetch_20newsgroups 中的目标名称匹配

http - 多线程Go for HTTP get

javascript - 如何以及在何处定义 Angular $http 默认值?