Search code examples
cookiespython-3.xsession-cookiespython-requests

How to add a cookie to the cookiejar in python requests library


I am trying to add a cookie to an existing cookiejar using the python requests 1.2.3 library. Every time I add the new cookie, the data in the jar is munged for the new cookie. Keys missing, Values missing or matched to incorrect Keys. I'm not sure if it's a Request library bug or I'm not sending the cookie correctly. I'm using the following code that is resulting in a bad cookie in cookiejar. Am I formatting the cookie correctly? Any ideas?

    my_cookie = {
           'domain':'www.mydomain.com',
           'expires':None,
           'name':'COOKIE_NAME',
           'path':'/',
           'value':'the cookie works',
           'version':0
}

s = requests.Session()
requests.utils.add_dict_to_cookiejar(s.cookies, my_cookie)

Solution

  • I found out a way to do it by importing CookieJar, Cookie, and cookies. With help from @Lukasa, he showed me a better way. However, with his way I was not able to specify the "port_specified", "domain_specified", "domain_initial_dot" or "path_specified" attributes. The "set" method does it automatically with default values. I'm trying to scrape a website and their cookie has different values in those attributes. As I am new to all of this I'm not sure if that really matters yet.

    my_cookie = {
    "version":0,
    "name":'COOKIE_NAME',
    "value":'true',
    "port":None,
    # "port_specified":False,
    "domain":'www.mydomain.com',
    # "domain_specified":False,
    # "domain_initial_dot":False,
    "path":'/',
    # "path_specified":True,
    "secure":False,
    "expires":None,
    "discard":True,
    "comment":None,
    "comment_url":None,
    "rest":{},
    "rfc2109":False
    }
    
    s = requests.Session()
    s.cookies.set(**my_cookie)