简体   繁体   English

Python:如何获取request.Session()的标头和有效载荷信息?

[英]Python: How to obtain headers and payload information for requests.Session()?

In Python, how can I obtain headers and payload information for a particular website to make requests via requests.Session() ? 在Python中,如何获取特定网站的headerspayload信息,以通过requests.Session()发出请求?

eg: 例如:

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'
}

Thank you in advance and will be sure to upvote and accept answer 预先谢谢您,一定会投票并接受答案

Most of those headers are automatically supplied by the requests module. 这些标头中的大多数都是由requests模块自动提供的。 Here is an example: 这是一个例子:

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'

The output of the pprint() call is this: pprint()调用的输出是这样的:

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

As you can see, s.get() fills in several headers. 如您所见, s.get()填充了多个标头。

A response object has a headers attribute: response对象具有headers属性:

import requests

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

Output: 输出:

>> {
    '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',
     ...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM