【问题标题】:Python requests library added an additional header "Accept-Encoding: identity"Python 请求库添加了一个额外的标头“Accept-Encoding: identity”
【发布时间】:2013-09-13 07:23:16
【问题描述】:

这是我的代码。

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 得到的。如您所见,它添加了一个额外的标题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。

谁能给点建议?

谢谢。

【问题讨论】:

  • 这太奇怪了。您使用什么版本的请求?除了文档之外,他们的存储库中没有“身份”一词。
  • 是的,我搜索了存储库并得到了与您描述的相同的结果。我使用请求 1.2.3。我找到了一个链接,似乎我的问题存在于该页面中:github.com/kennethreitz/requests/issues/…
  • 我愿意打赌(不是很多......)添加额外标题的是代理,而不是requests。你在 localhost:8888 上运行了什么?
  • 看来我可能会输掉那个赌注;这可能是由requests 合并代理的标头和目标服务器的标头的方式引起的……如果您非常确定 #821 是您的问题,您应该将其发布为答案并接受您自己的答案。
  • 我使用 fiddler2 的内置代理服务器来调试我的 http 通信。我不确定是否是 fiddler2 添加了标题,但我会看看。谢谢。

标签: python http http-headers python-requests


【解决方案1】:

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

http.client 实际上是checks 如果在传递的标题字典中已经有一个accept-encoding,并且如果有它跳过添加identity 标题 - 唯一的问题是作为标题字典传递的东西是什么像这样:

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

那么为什么它不起作用? requests encodes 标头名称,如在 python3 中,str 对象与 bytes 对象相比始终是 False,在 http.client 中执行的检查失败...

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-24
    • 2017-12-27
    • 1970-01-01
    • 2018-04-28
    • 2015-04-20
    • 2011-03-08
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多