簡體   English   中英

Python:如何獲取request.Session()的標頭和有效載荷信息?

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

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

預先謝謝您,一定會投票並接受答案

這些標頭中的大多數都是由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()填充了多個標頭。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM