python (1) 获取cookie和使用cookie

python之requests获取cookie和使用cookie

  • 获取cookie
    • 方法一 requests.utils.dict_from_cookiejar()(推荐)
    • 方法二 遍历拼接
  • 使用cookie
    • 方法一
    • 方法二

获取cookie

方法一 requests.utils.dict_from_cookiejar()(推荐)

使用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))

使用cookie

方法一

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)

更符合一般的表达习惯

你可能感兴趣的:(python,python,开发语言)