How to save requests (python) cookies to a file?

前端 未结 10 1701
渐次进展
渐次进展 2020-11-30 17:35

How to use the library requests (in python) after a request

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
bot = requests.session         


        
10条回答
  •  暖寄归人
    2020-11-30 17:53

    I found that the other answers had problems:

    • They didn't apply to sessions.
    • They didn't save and load properly. Only the cookie name and value was saved, the expiry date, domain name, etc. was all lost.

    This answer fixes these two issues:

    import requests.cookies
    
    def save_cookies(session, filename):
        if not os.path.isdir(os.path.dirname(filename)):
            return False
        with open(filename, 'w') as f:
            f.truncate()
            pickle.dump(session.cookies._cookies, f)
    
    
    def load_cookies(session, filename):
        if not os.path.isfile(filename):
            return False
    
        with open(filename) as f:
            cookies = pickle.load(f)
            if cookies:
                jar = requests.cookies.RequestsCookieJar()
                jar._cookies = cookies
                session.cookies = jar
            else:
                return False
    

    Then just call save_cookies(session, filename) to save or load_cookies(session, filename) to load. Simple as that.

提交回复
热议问题