Python-requests获取cookie的方法

时间:2024-03-09 14:45:08

一. 处理cookie

  1. 处理cookie方法一:用 requests.utils.dict_from_cookiejar() 把返回的cookies转换成字典

 1 import requests
 2 
 3 def login():
 4     url = \'http://www.xxx.com/login
 5     headers = {
 6         \'Content-Type\': "application/json"
 7     }
 8     payload = {
 9         "usercode": "111@qq.com",
10         "password": "11111"
11     }
12     try:
13         res = requests.post(url, headers=headers, json=payload)
14         cookies = res.cookies
15 
16         cookie = requests.utils.dict_from_cookiejar(cookies)
17 
18         return cookie
19     except Exception as err:
20         print(\'获取cookie失败:\n{0}\'.format(err))

  2 处理cookie 方法二:遍历cookies的键值,拼接成cookie格式

 1 import requests
 2 
 3 def login():
 4     login_url = \'http://www.baidu.com/login
 5     headers = {
 6         \'Content-Type\': "application/json"
 7     }
 8     payload = {
 9         "usercode": "11111@qq.com",
10         "password": "1111"
11     }
12     try:
13         res = requests.post(url=login_url, headers=headers, json= payload)
14         cookies = res.cookies.items()
15 
16         cookie = \'\'
17         for name, value in cookies:
18             cookie += \'{0}={1};\'.format(name, value)
19 
20         return cookie
21     except Exception as err:
22         print(\'获取cookie失败:\n{0}\'.format(err))

二. 使用cookie

  方法一:

1 import requests
2 
3 def get_data():
4     cookie = login()
5     res = requests.get(url=get_data_url, cookies=cookie)
6     print(res.text)

  方法二:

1 import requests
2 
3 def get_data():
4     cookie = login()
5     headers = {
6         "cookie": cookie
7     }
8     res = requests.get(url=get_data_url, headers=headers)
9     print(res.text)