一. 处理cookie
- 方法一:用
requests.utils.dict_from_cookiejar()
把返回的cookies转换成字典
import requests def login(): url = 'http://www.xxx.com/login' headers = { 'Content-Type': "application/json" } payload = { "usercode": "[email protected]", "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))
- 方法二:遍历cookies的键值,拼接成cookie格式
import requests def login(): login_url = 'http://www.baidu.com/login' headers = { 'Content-Type': "application/json" } payload = { "usercode": "[email protected]", "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
- 方法一:
import requests def get_data(): cookie = login() res = requests.get(url=get_url, cookies=cookie) print(res.text)
- 方法二:
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
标签:cookies,headers,python,res,url,cookie,requests From: https://www.cnblogs.com/tslam/p/16717974.html