python requests模块获取与使用cookie

一. 处理cookie

  1. 方法一:用
    requests.utils.dict_from_cookiejar()把返回的cookies转换成字典
import requests 
def login():
    url = 'http://www.xxx.com/login'
    headers = { 
        'Content-Type': "application/json" 
    } 
    payload = {
       "usercode": "111@qq.com",
       "password": "11111"
    }    
    try:
        res = requests.post(url, headers=headers, json=payload)
        cookies = res.cookies
        cookie = requests.utils.dict_from_cookiejar(cookies)     
        return cookie
    except Exception as err:
        print('获取cookie失败:\n{0}'.format(err))

 



  1. 方法二:遍历cookies的键值,拼接成cookie格式
import requests 
def login(): 
    login_url = 'http://www.baidu.com/login'
    headers = { 
        'Content-Type': "application/json" 
    } 
    payload = { 
        "usercode": "11111@qq.com",
        "password": "1111"
    }    
    try:
        res = requests.post(url=login_url, headers=headers, json= payload)
        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

  1. 方法一:
import requests
def get_data():
    cookie = login()
    res = requests.get(url=get_url, cookies=cookie)
    print(res.text)

 

  1. 方法二:
import requests
def get_data():
   cookie = login()
   headers = {"cookie": cookie}
   res = requests.get(url=get_url, headers=headers)
   print(res.text)

 

转载:https://www.cnblogs.com/shukeshu/p/14747736.html

posted @ 2022-09-22 09:09  tslam  阅读(345)  评论(0编辑  收藏  举报