current position:Home>Solve the problem that the session of the requests Library in Python cannot save cookies

Solve the problem that the session of the requests Library in Python cannot save cookies

2022-02-02 15:04:49 adorable_

   When we are using Python Of requests When the library does interface automation , We all know that as long as you use session = requests.session() Will automatically save cookie
   But when I was working on the company's interface automation project , Found saved cookie Don't take effect , Print after logging in to the interface through the request cookie, I found that there was cookie, Here is my big head o(╥﹏╥)o
   After searching for multi-party data , At last I found the reason , original requests Can only keep cookiejar Type of cookie, And we built it manually cookie yes dict Type of . So we need to take dict To cookiejar type , The conversion method is as follows :

#  take CookieJar Turn to dictionary :
cookies_dict = requests.utils.dict_from_cookiejar(resp.cookies)

#  Turn the dictionary into CookieJar:
cookies = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
#  among cookie_dict Is to convert the dictionary 

#  After the conversion, you can assign it to cookies  And passed in to session It's in :
session = requests.Session()
session.cookies = cookies

   In actual use, you need to observe cookie Format , For example, our company will cookie With key-value In the request header , So my approach here is to cookie Turn to dictionary , Then splice the contents of the dictionary into strings .

copyright notice
author[adorable_],Please bring the original link to reprint, thank you.

Random recommended