本文目录导读:

我来详细介绍如何编写Cookie管理脚本,包含多种实现方式。
JavaScript (浏览器端) Cookie管理脚本
基础Cookie操作类
class CookieManager {
// 设置Cookie
static set(name, value, days = 7, path = '/', domain = '', secure = false) {
let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
// 过期时间
if (days) {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
cookieString += `; expires=${expires.toUTCString()}`;
}
// 路径、域、安全标志
cookieString += `; path=${path}`;
if (domain) cookieString += `; domain=${domain}`;
if (secure) cookieString += '; secure';
document.cookie = cookieString;
}
// 获取Cookie
static get(name) {
const cookies = document.cookie.split('; ');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.split('=');
if (decodeURIComponent(cookieName) === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
}
// 删除Cookie
static delete(name, path = '/', domain = '') {
this.set(name, '', -1, path, domain);
}
// 获取所有Cookie
static getAll() {
const cookies = {};
const cookieArray = document.cookie.split('; ');
cookieArray.forEach(cookie => {
if (cookie) {
const [name, value] = cookie.split('=');
cookies[decodeURIComponent(name)] = decodeURIComponent(value);
}
});
return cookies;
}
// 检查Cookie是否存在
static has(name) {
return this.get(name) !== null;
}
// 获取Cookie数量
static count() {
return document.cookie.split(';').filter(cookie => cookie.trim()).length;
}
// 清除所有Cookie
static clear() {
const cookies = this.getAll();
Object.keys(cookies).forEach(name => {
this.delete(name);
});
}
}
使用示例
// 设置Cookie
CookieManager.set('username', '张三', 7);
CookieManager.set('token', 'abc123', 30, '/', '.example.com', true);
// 获取Cookie
const username = CookieManager.get('username');
console.log(username); // 输出: 张三
// 检查Cookie
if (CookieManager.has('token')) {
console.log('Token存在');
}
// 删除Cookie
CookieManager.delete('username');
// 获取所有Cookie
const allCookies = CookieManager.getAll();
console.log(allCookies);
Python Cookie管理脚本
完整Cookie管理器
import http.cookiejar
import os
import json
from datetime import datetime, timedelta
import requests
class CookieManager:
def __init__(self, cookie_file=None):
self.cookie_jar = http.cookiejar.CookieJar()
self.cookie_file = cookie_file or 'cookies.json'
# 如果存在Cookie文件,加载它们
if os.path.exists(self.cookie_file):
self.load_cookies()
def set_cookie(self, name, value, domain='', path='/',
expires=None, secure=False, http_only=False):
"""设置Cookie"""
cookie = http.cookiejar.Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain=domain,
domain_specified=bool(domain),
domain_initial_dot=False,
path=path,
path_specified=True,
secure=secure,
expires=expires,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': http_only},
rfc2109=False
)
self.cookie_jar.set_cookie(cookie)
def get_cookie(self, name, domain='', path='/'):
"""获取Cookie值"""
for cookie in self.cookie_jar:
if cookie.name == name:
if (not domain or cookie.domain == domain) and cookie.path == path:
return cookie.value
return None
def delete_cookie(self, name, domain='', path='/'):
"""删除指定Cookie"""
cookies_to_remove = []
for cookie in self.cookie_jar:
if cookie.name == name:
if (not domain or cookie.domain == domain) and cookie.path == path:
cookies_to_remove.append(cookie)
for cookie in cookies_to_remove:
self.cookie_jar.clear(cookie.domain, cookie.path, cookie.name)
def save_cookies(self):
"""保存Cookie到文件"""
cookies_data = []
for cookie in self.cookie_jar:
cookie_dict = {
'name': cookie.name,
'value': cookie.value,
'domain': cookie.domain,
'path': cookie.path,
'secure': cookie.secure,
'expires': cookie.expires,
'httponly': cookie.has_nonstandard_attr('HttpOnly')
}
cookies_data.append(cookie_dict)
with open(self.cookie_file, 'w', encoding='utf-8') as f:
json.dump(cookies_data, f, indent=2, ensure_ascii=False)
print(f"Cookies已保存到 {self.cookie_file}")
def load_cookies(self):
"""从文件加载Cookie"""
try:
with open(self.cookie_file, 'r', encoding='utf-8') as f:
cookies_data = json.load(f)
for cookie_dict in cookies_data:
self.set_cookie(
name=cookie_dict['name'],
value=cookie_dict['value'],
domain=cookie_dict.get('domain', ''),
path=cookie_dict.get('path', '/'),
secure=cookie_dict.get('secure', False),
expires=cookie_dict.get('expires', None),
http_only=cookie_dict.get('httponly', False)
)
print(f"已从 {self.cookie_file} 加载Cookies")
except FileNotFoundError:
print("Cookie文件不存在")
except json.JSONDecodeError:
print("Cookie文件格式错误")
def export_to_netscape_format(self, output_file='cookies.txt'):
"""导出为Netscape格式"""
with open(output_file, 'w', encoding='utf-8') as f:
f.write("# Netscape HTTP Cookie File\n")
f.write("# 这是一个自动生成的文件,请勿手动修改\n\n")
for cookie in self.cookie_jar:
domain = cookie.domain or ''
domain_flag = 'TRUE' if domain.startswith('.') else 'FALSE'
path = cookie.path or '/'
secure = 'TRUE' if cookie.secure else 'FALSE'
expires = str(int(cookie.expires)) if cookie.expires else '0'
name = cookie.name
value = cookie.value
f.write(f"{domain}\t{domain_flag}\t{path}\t{secure}\t{expires}\t{name}\t{value}\n")
print(f"已导出为Netscape格式: {output_file}")
def get_all_cookies(self):
"""获取所有Cookie"""
cookies = {}
for cookie in self.cookie_jar:
cookies[cookie.name] = {
'value': cookie.value,
'domain': cookie.domain,
'path': cookie.path,
'secure': cookie.secure,
'httponly': cookie.has_nonstandard_attr('HttpOnly')
}
return cookies
def clear_all_cookies(self):
"""清除所有Cookie"""
self.cookie_jar.clear()
print("已清除所有Cookies")
def has_expired_cookies(self):
"""检查是否有过期Cookie"""
now = datetime.now().timestamp()
for cookie in self.cookie_jar:
if cookie.expires and cookie.expires < now:
return True
return False
def clean_expired_cookies(self):
"""清理过期Cookie"""
now = datetime.now().timestamp()
expired_count = 0
for cookie in list(self.cookie_jar):
if cookie.expires and cookie.expires < now:
self.cookie_jar.clear(cookie.domain, cookie.path, cookie.name)
expired_count += 1
if expired_count > 0:
print(f"已清理 {expired_count} 个过期Cookie")
# 使用Requests会话的例子
class SessionWithCookieManager:
def __init__(self, cookie_manager=None):
self.session = requests.Session()
self.cookie_manager = cookie_manager or CookieManager()
# 如果Cookie管理器中有Cookie,加载到会话中
if self.cookie_manager:
self.session.cookies = self.cookie_manager.cookie_jar
def get(self, url, **kwargs):
return self.session.get(url, **kwargs)
def post(self, url, data=None, **kwargs):
return self.session.post(url, data=data, **kwargs)
def save_session_cookies(self):
"""保存当前会话的Cookies"""
self.cookie_manager.cookie_jar = self.session.cookies
self.cookie_manager.save_cookies()
def load_session_cookies(self):
"""加载保存的Cookies到会话"""
self.cookie_manager.load_cookies()
self.session.cookies = self.cookie_manager.cookie_jar
使用示例
# 创建Cookie管理器
cm = CookieManager()
# 设置Cookie
cm.set_cookie('session_id', 'abc123', '.example.com', expires=datetime.now().timestamp() + 86400)
cm.set_cookie('user_preferences', '{"theme":"dark"}', '.example.com')
# 获取Cookie
session = cm.get_cookie('session_id')
print(f"Session ID: {session}")
# 保存Cookies
cm.save_cookies()
# 使用会话管理器
session_mgr = SessionWithCookieManager(cm)
response = session_mgr.get('https://example.com')
session_mgr.save_session_cookies()
# 清理过期Cookie
cm.clean_expired_cookies()
# 导出为Netscape格式
cm.export_to_netscape_format()
Chrome扩展Cookie管理脚本
// manifest.json
{
"manifest_version": 3,
"name": "Cookie Manager",
"version": "1.0",
"permissions": [
"cookies",
"storage",
"activeTab"
],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "popup.html"
}
}
// popup.js
class ChromeCookieManager {
// 获取所有Cookie
static async getAllCookies(domain) {
return new Promise((resolve) => {
chrome.cookies.getAll({ domain: domain }, (cookies) => {
resolve(cookies);
});
});
}
// 设置Cookie
static async setCookie(details) {
return new Promise((resolve) => {
chrome.cookies.set(details, (cookie) => {
resolve(cookie);
});
});
}
// 删除Cookie
static async removeCookie(url, name) {
return new Promise((resolve) => {
chrome.cookies.remove({ url: url, name: name }, (details) => {
resolve(details);
});
});
}
// 导出Cookies为JSON
static async exportCookies(domain) {
const cookies = await this.getAllCookies(domain);
return JSON.stringify(cookies, null, 2);
}
// 导入Cookies
static async importCookies(cookiesJson) {
const cookies = JSON.parse(cookiesJson);
for (const cookie of cookies) {
await this.setCookie({
url: `https://${cookie.domain}${cookie.path}`,
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
httpOnly: cookie.httpOnly,
sameSite: cookie.sameSite
});
}
}
}
这些脚本提供了完整的Cookie管理功能,你可以根据实际需求选择适合的实现方式。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播