How to get cookie after login using mechanize

Question:

import mechanize
import json
import re
from bs4 import BeautifulSoup
import requests

browser = mechanize.Browser()
class login:
    def __init__(self):
        email = "aaaa"
        password = "bbb"
        url = "https://app.propertymeld.com/login/?next=/"
        self.email = email
        self.password= password
        self.url = url
    def login_url(self):
        try:
            browser.open(self.url)
            browser.select_form(nr=0)
            browser.form['email'] = self.email
            browser.form['password'] = self.password
            result = browser.submit().read()
            print(result)
            print("Login Successfully")
        except Exception as e:
            print("Unable to login successfully",e)

def main():
    web_login = login()
    web_login.login_url()
if __name__ == "__main__":
    main()

I need to get the cookies after logging in a webpage, using a particular email and password with mechanize. How can I get the browser’s cookies in a particular login session?

Asked By: Ajay

||

Answers:

You can get the cookies from browser._ua_handlers['_cookies'].cookiejar.
This returns a mechanize._clientcookie.CookieJar object which can be iterated through and there are names and values for each of the cookies in it.

For instance, the first cookie’s name and value are:
browser._ua_handlers['_cookies'].cookiejar[0].name
browser._ua_handlers['_cookies'].cookiejar[0].value

Answered By: Amir Zare
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.