【问题标题】:Python: How to obtain headers and payload information for requests.Session()?Python:如何获取 requests.Session() 的 headers 和 payload 信息?
【发布时间】:2017-08-22 00:09:04
【问题描述】:

在 Python 中,如何获取特定网站的 headerspayload 信息以通过 requests.Session() 发出请求?

例如:

headers = {
            'Host': 'www.testsite.com',
            'Accept': 'application/json',
            'Proxy-Connection': 'keep-alive',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'en-us',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'http://www.testsite.com',
            'Connection': 'keep-alive',
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257',
            'Referer': 'http://www.testsite.com/mobile'
}

提前谢谢你,一定会投票并接受答案

【问题讨论】:

  • 您将自己的标头构建为您想要的任何东西,所以我不确定您所说的“我如何获取标头?”是什么意思。您的意思是“我如何发现主机想要接收的标头?”

标签: python python-2.7 http-headers python-requests payload


【解决方案1】:

大多数这些标头由requests 模块自动提供。这是一个例子:

import requests
from pprint import pprint

with requests.Session() as s:
    s.get('http://httpbin.org/cookies/set?name=joe')
    r = s.get('http://httpbin.org/cookies')
    pprint(dict(r.request.headers))

assert r.json()['cookies']['name'] == 'joe'

pprint() 调用的输出是这样的:

{'Accept': '*/*',
 'Accept-Encoding': 'gzip, deflate',
 'Connection': 'keep-alive',
 'Cookie': 'name=joe',
 'User-Agent': 'python-requests/2.9.1'}

如您所见,s.get() 填充了几个标题。

【讨论】:

  • 感谢您的回复!至于特定路线的有效载荷,例如http://www.testsite.com/students.json,您如何真正找出站点可用的路线?为什么它有例如students.json?
  • 我很确定您提到的 URL 不是真实的。如果您告诉我们您使用的实际 URL,人们可能会提供帮助。
  • 例如https://shop-usa.palaceskateboards.com/collections/hardware 我检查了Network 下的谷歌开发工具,但为什么它不显示他们在哪里进行 API 调用、获取 json 数据并用项目填充页面?
  • @JoKo - 是什么让你相信 Palaceskateboards.com 有一个 API?
【解决方案2】:

response 对象具有 headers 属性:

import requests

with requests.Session() as s:
    r = s.get("http://google.es")
    print(r.headers)

输出:

>> {
    'Date': 'Tue, 22 Aug 2017 00:37:13 GMT', 
    'Expires': '-1', 
    'Cache-Control': 'private, 
     max-age=0', 
     'Content-Type': 'text/html; charset=ISO-8859-1',
     ...
    }

【讨论】:

  • 感谢您的回复!至于特定路线的有效载荷,例如http://www.testsite.com/students.json,您如何真正找出站点可用的路线?为什么它有例如students.json?
猜你喜欢
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
相关资源
最近更新 更多