You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:09:04