Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching cookies from a file with python

I'm using mechanize and python to log into a site. I've created two functions. The first one logs in and the second one searches the site. How exactly do I store the cookies from the login so when I come to searching I have a cookie.

Current code.

import mechanize
import cookielib

def login(username, password):
    # Browser
    br = mechanize.Browser()

    # Cookie Jar
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)
    cj.save('cookies.txt', ignore_discard=False, ignore_expires=False)
    # Rest of login

def search(searchterm):

    # Browser
    br = mechanize.Browser()

    # Cookie Jar
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)
    cj.load('cookies.txt', ignore_discard=False, ignore_expires=False)
    # Rest of search

I read through the cookielib info page but there aren't many examples there and I haven't been able to get it working. Any help would be appreciated. Thanks

like image 460
Michael Esteves Avatar asked Feb 09 '26 22:02

Michael Esteves


1 Answers

You need to use the same browser instance, obviously:

def login(browser, username, password):
  # ...

def search(browser, searchterm):
  # ...

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
cj.load('cookies.txt', ignore_discard=False, ignore_expires=False)
login(br, "user", "pw")
search(br, "searchterm")

Now that you have common context, you should probably make a class out of it:

class Session(object):
  def __init__(browser):
    self.browser = browser

  def login(user, password):
    # ... can access self.browser here

  def search(searchterm):
    # ... can access self.browser here

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
cj.load('cookies.txt', ignore_discard=False, ignore_expires=False)
session = Session(br)
session.login("user", "pw")
session.search("searchterm")
like image 115
Niklas B. Avatar answered Feb 12 '26 16:02

Niklas B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!