I've recently been working on a script that accesses a website's form to log in. Tried with requests but it seems that mechanize works better for this application. Was asking around and I wrote this code which does work:
mCookieJar = mechanize.CookieJar()
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_equiv(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Manjaro; U; Linux x86_64; en-US; rv:1.9.0.1)')]
br.set_cookiejar(mCookieJar)
br.open(LoginUrl)
br.select_form(action="/takelogin.php")
br['email'] = Username
br['password'] = Password
resp = br.submit()
This works fine, but it creates a new session cookie every time the script is run. This is not ideal as in my user preferences for this website, I end up with a HUGE list of sessions that I need to manually close. The website does have another way around this for automated scripts - you can generate a permanent cookie just for this purpose.
However, I have no idea what mechanize.CookieJar() is. I can't find any mention of this method or class in the Python mechanize documentation. There are a couple different cookiejar libs out there, but I don't need to include any of them for this to work.
So what is this class? Is it part of mechanize? How can I manually add cookies to it? There are some set_cookie() methods for the mechanize.Browser() class but I have no idea if these automatically add them to the active cookiejar. It seems very strange to me that this code works, and there are examples online using mechanize.CookieJar(), yet there is no mention of this anywhere in the documentation.
Browsing through the source it seems like
mechanizeis re-exportingCookieJarfrom eithercookielib(Python2) orhttp.cookiejar(Python3).Having that said, if you want to persist your cookie across different runs of the script you should probably be using
FileCookieJarinstead. This also gets re-exported the same way:cookielib.FileCookieJar(Python2)http.cookiejar.FileCookieJar(Python3)