他们说可以按以下顺序发送标头: http://docs.python-requests.org/en/master/user/advanced/#header-ordering
但是由于某些未知原因,请求从不按顺序发送标头。
示例代码:
headers01 = OrderedDict([("Connection", "close"), ("Upgrade-Insecure-Requests", "1"), ("User-Agent", "SomeAgent"), ("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8"), ("Accept-Encoding", "gzip, deflate"), ("Accept-Language", "Some Language")])
结果:
Connection: close
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)
Accept-Language: en-US,en;q=0.5
Upgrade-Insecure-Requests: 1
我的请求已由会话发送,并且如果未按会话发送,也无法正常工作。
答案 0 :(得分:1)
如果您阅读链接的文档页面,它确实表明了默认标题的局限性和解决方法...
运行此代码:
import requests
from collection import OrderedDict
headers = OrderedDict([("Connection", "close"), ("Upgrade-Insecure-Requests", "1"), ("User-Agent", "SomeAgent"), ("Accept", "text/html,application/xhtml+xml,applic
ation/xml;q=0.9,image/webp,image/apng,/;q=0.8"), ("Accept-Encoding", "gzip, deflate"), ("Accept-Language", "Some Language")])
s = requests.Session()
s.headers = headers
r = s.get(http://localhost:6000/foo)
发送:
GET /foo HTTP/1.1\r\nHost: localhost:6000\r\nConnection: close\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: SomeAgent\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8\r\nAccept-Encoding:
gzip, deflate\r\nAccept-Language: Some Language\r\n\r\n
答案 1 :(得分:0)
您实际上是错误的:标头顺序无关紧要,无论如何都不符合标准https://tools.ietf.org/html/rfc2616
您要说明的重点(即为什么如此重要)是,可以基于碰巧使用的标头顺序通过指纹识别(有点不可靠)浏览器。很好,但这绝不是Python库实现特定顺序的原因。
令您失望的是,您将无法使用该库来模拟某些浏览器或无法通过这种类型的软件准确地进行指纹识别,但这太可惜了,但这很难证明问题的根源。
这里最好的建议是找到一个备用http请求库,该库允许特定的标头排序并保证维持您提供的顺序。