如何使用Mechanize在登录后获取网页会话Cookie
你现有的登录代码如下:
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()
要在登录成功后获取会话Cookie,只需利用Mechanize Browser对象自带的cookiejar属性——它会自动维护当前会话的所有Cookie信息。修改后的代码如下:
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("Login Successfully") # 获取并打印会话中的Cookie详情 print("\n当前会话Cookie详情:") for cookie in browser.cookiejar: print(f"名称: {cookie.name}, 值: {cookie.value}, 域名: {cookie.domain}, 路径: {cookie.path}") # 转换成字典格式,方便后续业务使用 cookie_dict = {cookie.name: cookie.value for cookie in browser.cookiejar} print("\nCookie字典格式:", cookie_dict) except Exception as e: print("Unable to login successfully",e) def main(): web_login = login() web_login.login_url() if __name__ == "__main__": main()
关键说明:
- Mechanize的
Browser实例会自动处理Cookie的存储和管理,登录操作完成后,browser.cookiejar中就保存了当前会话的所有Cookie。 - 遍历
cookiejar可以查看每个Cookie的完整属性(包括域名、路径、有效期等),满足精细化需求。 - 转换成字典格式后,Cookie可以直接用于其他HTTP请求库(比如requests),实现会话复用。
内容的提问来源于stack exchange,提问作者Ajay
相关产品推荐
相关产品推荐

