Python脚本使用网站的Cookies发送JSON请求

问题描述 投票:0回答:3

我正在尝试模仿经过身份验证的JSON请求。我正在使用请求模块执行此操作。

import requests
import json

url = "https://"
headers = {
    'Host': 'example.com',
    'content-type': 'application/json',
    'Connection': 'keep-alive'
}

data = {
"asdsdsd": {
    "AppName": "esdf",
    "Language": "EN",
    "fsef": [
        {
            "sfddf": [
                {
                    "sdfsdfsdf": "sdfsdfsdf"
                }
            ]
        }
    ]
},
"sdfdf": {
    "sdfsdf": "sdfsdfsdf"
}
}

r = requests.post(url, data=json.dumps(data), headers=headers ,verify=False)

我如何将经过身份验证的cookie包含在其中。

我可以使用浏览器(带有标题和数据)打开此请求,然后我就可以使用浏览器的经过身份验证的cookie。

有没有办法做到这一点?

python python-requests
3个回答
1
投票

使用Session object管理cookie。

Session

0
投票
s = requests.Session()

# load initial page to get session cookies set, perhaps a CSRF token
loginform = s.get(loginurl)

# post login information to the form
s.post(someurl, data={...})

# post JSON with session with authentication cookie
s.post(someurl, ...)

您可以使用会话进行发布

headers = {
'Host': 'example.com',
'content-type': 'application/json',
'Connection': 'keep-alive'
}

session = requests.session()
session.headers=headers

0
投票

您可以像这样在请求中将数据直接传递为cookie的形式:

session.post(url, data=json.dumps(data) ,verify=False)

完成:)

© www.soinside.com 2019 - 2024. All rights reserved.