简体   繁体   中英

Adding new cookies with Mechanize Python

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

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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM