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

前端 未结 10 1720
渐次进展
渐次进展 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条回答
  •  旧时难觅i
    2020-11-30 17:41

    Expanding on @miracle2k's answer, requests Sessions are documented to work with any cookielib CookieJar. The LWPCookieJar (and MozillaCookieJar) can save and load their cookies to and from a file. Here is a complete code snippet which will save and load cookies for a requests session. The ignore_discard parameter is used to work with httpbin for the test, but you may not want to include it your in real code.

    import os
    from cookielib import LWPCookieJar
    
    import requests
    
    
    s = requests.Session()
    s.cookies = LWPCookieJar('cookiejar')
    if not os.path.exists('cookiejar'):
        # Create a new cookies file and set our Session's cookies
        print('setting cookies')
        s.cookies.save()
        r = s.get('http://httpbin.org/cookies/set?k1=v1&k2=v2')
    else:
        # Load saved cookies from the file and use them in a request
        print('loading saved cookies')
        s.cookies.load(ignore_discard=True)
        r = s.get('http://httpbin.org/cookies')
    print(r.text)
    # Save the session's cookies back to the file
    s.cookies.save(ignore_discard=True)
    

提交回复
热议问题