使用requests.utils.dict_from_cookiejar()把返回的cookies转换成字典
def get_cookie():
url = "http://xxx"
header = {
"Content-Type": "application/json; charset=UTF-8",
"xxx": "xxx"
}
body = {
"xxx": "xxx",
"xxx": "xxx"}
try:
res = requests.post(url, headers=header, json=body, verify=False)
cookie = requests.utils.dict_from_cookiejar(res.cookies)
cookie = "c-token=" + cookie["c-token"]
return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))
遍历cookies的键值,拼接成cookie格式
def get_cookie():
url = "http://xxx"
header = {
"Content-Type": "application/json; charset=UTF-8",
"xxx": "xxx"
}
body = {
"xxx": "xxx",
"xxx": "xxx"}
try:
res = requests.post(url, headers=header, json=body, verify=False)
cookies = res.cookies.items()
cookie = ''
for name, value in cookies:
cookie += '{0}={1};'.format(name, value)
return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))
import requests
def get_data():
cookie = get_cookie()
res = requests.get(url=xxxxx, cookies=cookie)
print(res.text)
比较简洁高效
import requests
def get_data():
cookie = get_cookie()
headers = {"cookie": cookie}
res = requests.get(url=xxxxxx, headers=headers)
print(res.text)
更符合一般的表达习惯