Adding new cookies with Mechanize Python
Question: I am trying to add cookies to a browser in mechanize so I am not redirected to
a click ok to agree page.

I have looked but can figure out how to do this.

I can do it using urllib2 already but wish to do it with mechanize

    
    
    import urllib2
    
    opener = urllib2.build_opener()
    
    opener.addheaders.append(('Cookie', 'ASPSESSIONIDAEBDRQRT=HBODDIACJNHNMHNHBBIHOEGO; ASPSESSIONIDCEAATTSQ=ECNDDBKCJBMAHBIJOCJAEPEO'))
    
    u = opener.open("https://www.transactionservices.dla.mil/daasinq/dodaac.asp")
    

How do I add that cookie string in mechanize? Thanks in advance


Answer: By using cookielib and Cookie built-in libraries to set cookies and append
them to your mechanize session.

    
    
    import Cookie
    import cookielib
    cookiejar =cookielib.LWPCookieJar()
    
    br = mechanize.Browser()
    br.set_cookiejar(cookiejar)
    cookie = cookielib.Cookie('ASPSESSIONIDAEBDRQRT=HBODDIACJNHNMHNHBBIHOEGO; ASPSESSIONIDCEAATTSQ=ECNDDBKCJBMAHBIJOCJAEPEO')
    cookiejar.set_cookie(cookie)
    

AND Also, you can still add headers to your mechanize session:

    
    
    br.addheaders = [('Cookie','cookiename=cookie value')]
    

