requests获取cookie和使用cookie的方法
原文地址:https://www.cnblogs.com/liuzhzhao/p/12114453.html,感谢博主!
一. 用 requests.utils.dict_from_cookiejar() 把返回的cookies转换成字典
1. 处理cookies:
1 import requests
2
3 def login():
4 login_url = 'http://www.xxx.com/login
5 headers = {
6 "Accept": "application/json, text/javascript, */*; q=0.01"
7 }
8 body = {
9 "usercode": "liuzz05@****.com",
10 "password": "123456"
11 }
12 try:
13 res = requests.post(url=login_url, headers=headers, data=body)
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作为参数传入(建议使用这种,第二种有时候会失败,具体原因还请大神请教。其实最好的方式还是用requests.Session()这种方式保存cookie状态最好https://i.cnblogs.com/posts/edit;postId=12692370)
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)
二. 遍历cookies的键值,拼接成cookie格式
1. 处理cookies:
1 import requests
2
3 def login():
4 login_url = 'http://www.xxx.com/login
5 headers = {
6 "Accept": "application/json, text/javascript, */*; q=0.01"
7 }
8 body = {
9 "usercode": "liuzz05@****.com",
10 "password": "123456"
11 }
12 try:
13 res = requests.post(url=login_url, headers=headers, data=body)
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))
2. 使用cookie:
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)


浙公网安备 33010602011771号