Python请求库添加了一个额外的标题"Accept-Encoding:identity"

Jus*_*ner 5 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)
Run Code Online (Sandbox Code Playgroud)

这是我从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
Run Code Online (Sandbox Code Playgroud)

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

有人可以给点建议吗?

谢谢.

mat*_*ata 6

这起源于 的内部深处http.client,被使用urllib3,被使用requests

http.client实际上检查是否已经accept-encoding传递了 headers 字典中的an ,如果存在则跳过添加identity标头 - 唯一的问题是作为 headers 字典传递的内容是这样的:

CaseInsensitiveDict({b'Accept-Encoding': 'gzip, deflate, compress', ...})
Run Code Online (Sandbox Code Playgroud)

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

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

编辑
这似乎已在(尚未发布)2.0 请求分支中修复