python-3.xcookiespython-requestsmechanicalsoupcookielib

How to add a cookie to existing cookies in MechanicalSoup


I know MechanicalSoup has a function called set_cookiejar() but it replaces the current cookiejar completely. I want to know how to add new cookies to existing cookies.


Solution

  • You can achieve it like this

    import mechanicalsoup
    
    browser = mechanicalsoup.StatefulBrowser()
    browser.open("your website")
    
    cookie_obj = requests.cookies.create_cookie(name='cookie name', value='cookie value', domain='domain name')
    browser.session.cookies.set_cookie(cookie_obj)  # This will add your new cookie to existing cookies
    

    Another way to do it is

    import mechanicalsoup
    
    browser = mechanicalsoup.StatefulBrowser()
    browser.open("your website")
    
    new_cookie = {
        "name":'COOKIE_NAME',
        "value":'true',
        "version":0,
        "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
    }
    
    browser.session.cookies.set(**new_cookie)   # This will add your new cookie to existing cookies
    

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