一. 处理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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐