使用Python获取cookie的value值并保存为txt文件的简便方法有哪些?
Python Selenium 实现方法
driver.get_cookie() 本身返回的就是标准字典结构,直接读取value键对应的值即可,两种常用写法:
- 确认目标cookie一定存在时可以直接取值:
cookie_value = driver.get_cookie("cookie-name-here")["value"]
- 避免cookie不存在抛出
KeyError的稳妥写法:
target_cookie = driver.get_cookie("cookie-name-here") if target_cookie: cookie_value = target_cookie.get("value") else: # 此处可自定义cookie不存在时的处理逻辑 print("未找到指定名称的cookie")
JavaScript 实现方法
浏览器原生JS(控制台/前端脚本直接可用)
不需要依赖任何工具,直接通过document.cookie解析获取指定值:
function getCookie(name) { const cookieStr = `; ${document.cookie}`; const cookieArr = cookieStr.split(`; ${name}=`); if (cookieArr.length === 2) return cookieArr.pop().split(';').shift(); } // 调用示例 const targetCookieValue = getCookie("cookie-name-here");
Selenium for JS 写法
和Python版本逻辑一致,直接读取返回对象的value属性即可:
// 需要在async函数内调用 const targetCookie = await driver.manage().getCookie("cookie-name-here"); const cookieValue = targetCookie?.value;
内容的提问来源于stack exchange,提问作者user262670
相关产品推荐
相关产品推荐

