如何在python中通过请求传递参数或cookie?

时间:2019-12-02 16:41:48

标签: python-3.x automation python-requests

使用以下方法提取Cookie和参数时遇到问题

检查元素->网络(Firefox)

我正在尝试通过我的请求

使用以下代码:

import requests

cookies ={"_ga":"GA","cookid":"cookies","cookname":"username","id":"id_num","ider":"ider","PHPSESSID":"PHPSESSID","tb":"tb_num"}
params ={"Query string":{"sec":"8"},"Form data":{"chk[]":["on","on","on"],"sec":"8","add-final":""}}
url = 'https://url.com/add.php?sec=8'

r = requests.post(url, cookies=cookies, params=params)

print(r.cookies)

(为了安全起见,我更改了cookie)

并在打印cookie时返回以下内容:

<RequestsCookieJar[]>

2 个答案:

答案 0 :(得分:0)

r.cookies不会为您获取请求的cookie,而是为您获取在请求响应中收到的cookie。

要获取已发送的Cookie,

r.request.cookies

答案 1 :(得分:0)

可能与您发送POST请求的方式相关联,请尝试替换以下内容:

r = requests.post(url, cookies=cookies, params=params)

与此:

r = requests.post(url, cookies=cookies, data=params)

此外,如果您尝试以字典的形式打印cookie,则应使用:

print(r.cookies.get_dict())

希望这会有所帮助