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

前端 未结 10 1727
渐次进展
渐次进展 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:51

    code for python 3

    Note that the great majority of cookies on the Internet are Netscape cookies. so if you want to save cookies to disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers) use MozillaCookieJar

    from http.cookiejar import MozillaCookieJar
    import requests
    
    s = requests.Session()
    s.cookies = MozillaCookieJar('cookies.txt')
    # or s.cookies = MozillaCookieJar() and later use s.cookies.filename = 'cookies.txt' or pass the file name to save method.
    
    response = s.get('https://www.msn.com')
    
    s.cookies.save()
    

    the file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods.

    Note that the save() method won’t save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.

    s.cookies.save(ignore_discard=True)
    

    using load method:

    load cookies from a file.

    Old cookies are kept unless overwritten by newly loaded ones.

    s.cookies.load()
    

    using revert method:

    Clear all cookies and reload cookies from a saved file.

    s.cookies.revert()
    

    you may need also to pass a true ignore_discard argument in load or revert methods.

    note about using MozillaCookieJar :

    Note This loses information about RFC 2965 cookies, and also about newer or non-standard cookie-attributes such as port.

    more reading

提交回复
热议问题