如何使用Python的nodriver库保存和加载会话(Cookies)?
问题说明
作为Python新手,尝试用nodriver保存和加载会话Cookie时,发现网上示例代码过时,尝试多种方法后仍未能实现第二次启动程序时自动处于登录状态,现有可执行登录代码如下,需添加Cookie持久化逻辑:
# 原代码 import asyncio import nodriver as uc user = "User" password = "passwort" async def type_text(element, text): for char in text: await element.send_keys(char) async def main(): browser = None try: browser = await uc.start() page = await browser.get('https://html-php.de/php/zb_php_f/index.php') email_field = await page.select("input[name=a_nick]") password_field = await page.select("input[name=a_pass]") login_task = None if email_field and password_field: await type_text(email_field, user) await type_text(password_field, password) login_button = await page.select("input[type=submit]") if login_button: login_task = asyncio.create_task(login_button.click()) if login_task: await login_task except Exception as e: print(f"Error during login: {e}") finally: if browser: await asyncio.sleep(10) await browser.stop() if __name__ == '__main__': uc.loop().run_until_complete(main())
解决方案
通过page.get_cookies()获取登录后的Cookie并保存为JSON文件;启动程序时先读取该文件,用page.add_cookie()将Cookie注入浏览器会话,实现免登录。
修改后完整代码
import asyncio import nodriver as uc import json import os # 配置信息 user = "User" password = "passwort" COOKIE_FILE = "session_cookies.json" TARGET_URL = 'https://html-php.de/php/zb_php_f/index.php' async def type_text(element, text): for char in text: await element.send_keys(char) def save_cookies(cookies, file_path): """将Cookie保存到JSON文件""" with open(file_path, 'w', encoding='utf-8') as f: json.dump(cookies, f, indent=2) def load_cookies(file_path): """从JSON文件加载Cookie""" if not os.path.exists(file_path): return None with open(file_path, 'r', encoding='utf-8') as f: return json.load(f) async def is_logged_in(page): """判断是否已登录:检查登录框是否不存在""" try: email_field = await page.select("input[name=a_nick]", timeout=2) return not email_field # 找不到登录框则视为已登录 except Exception: return True async def main(): browser = None try: browser = await uc.start() page = await browser.get(TARGET_URL) # 尝试加载本地Cookie cookies = load_cookies(COOKIE_FILE) if cookies: for cookie in cookies: # 修正Cookie域名,确保与目标网站匹配 if 'domain' not in cookie or cookie['domain'].startswith('.'): cookie['domain'] = '.html-php.de' try: await page.add_cookie(cookie) except Exception as e: print(f"添加Cookie失败: {e}") # 重新加载页面使Cookie生效 await page.get(TARGET_URL) # 检查登录状态 if not await is_logged_in(page): # 执行登录流程 email_field = await page.select("input[name=a_nick]") password_field = await page.select("input[name=a_pass]") login_task = None if email_field and password_field: await type_text(email_field, user) await type_text(password_field, password) login_button = await page.select("input[type=submit]") if login_button: login_task = asyncio.create_task(login_button.click()) await login_task # 等待页面加载完成后保存Cookie await asyncio.sleep(2) session_cookies = await page.get_cookies() save_cookies(session_cookies, COOKIE_FILE) print("已保存登录Cookie") else: print("未找到登录输入框,页面结构可能已变化") else: print("已通过Cookie自动登录") await asyncio.sleep(10) except Exception as e: print(f"执行出错: {e}") finally: if browser: await browser.stop() if __name__ == '__main__': uc.loop().run_until_complete(main())
关键说明
- Cookie持久化:用JSON文件存储Cookie,
save_cookies和load_cookies函数负责读写操作 - Cookie有效性:添加Cookie时需确保
domain参数与目标网站匹配,否则Cookie无法生效 - 登录状态判断:通过检查登录输入框是否存在判断登录状态,可根据目标网站实际结构调整逻辑
- 异常处理:处理Cookie文件不存在、添加Cookie失败等场景,避免程序崩溃
内容的提问来源于stack exchange,提问作者Aca
相关产品推荐
相关产品推荐

