Add multi-browser support and HTTP fallback for cookie acquisition

This commit is contained in:
2026-03-02 21:48:13 +08:00
parent 0f3dd8f287
commit 74d40cea4f
2 changed files with 249 additions and 387 deletions

434
README.md
View File

@@ -1,370 +1,140 @@
# 抖音去水印下载器 v3.0
![项目图](https://tvax2.sinaimg.cn/large/006908GAly1hgn9zod1yuj30zk0hstmf.jpg)
自动Cookie | 无需登录 | 一键下载 | 支持多环境
<h1 align="center">✨ 抖音去水印作品下载 ✨</h1>
<div align="center">
## ✨ 特性
[English](README-EN.md) | 简体中文
-**自动Cookie获取** - 无需手动操作
-**多浏览器支持** - Edge/Chrome/Firefox
-**HTTP请求方式** - 无浏览器也能用
-**GUI界面** - 简单易用
-**无水印下载** - 高清原画
-**多模式下载** - 单个/主页/喜欢/收藏等
[![License: MIT](https://img.shields.io/github/license/johnserf-seed/tiktokdownload?style=for-the-badge)](https://github.com/Johnserf-Seed/TikTokDownload/blob/main/LICENSE)
![Release Download](https://img.shields.io/github/downloads/Johnserf-Seed/TikTokDownload/total?style=for-the-badge)
![GitHub Repo size](https://img.shields.io/github/repo-size/Johnserf-Seed/TikTokDownload?style=for-the-badge&color=3cb371)
[![GitHub Repo Languages](https://img.shields.io/github/languages/top/Johnserf-Seed/TikTokDownload?style=for-the-badge)](https://github.com/BeyondDimension/SteamTools/search?l=c%23)
[![Python v3.11.1](https://img.shields.io/badge/python-v3.11.1-orange?style=for-the-badge)](https://github.com/Johnserf-Seed/TikTokDownload)
![Terminal: wt](https://img.shields.io/badge/Terminal-wt-blue?style=for-the-badge)
## 🚀 快速开始
[![GitHub Stars](https://img.shields.io/github/stars/johnserf-seed/tiktokdownload?style=social)](https://github.com/Johnserf-Seed/TikTokDownload)
[![GitHub Forks](https://img.shields.io/github/forks/johnserf-seed/tiktokdownload?style=social)](https://github.com/Johnserf-Seed/TikTokDownload)
[![GitHub Issues](https://img.shields.io/github/issues/johnserf-seed/tiktokdownload?style=social)](https://github.com/Johnserf-Seed/TikTokDownload)
[![GitHub Closed Issues](https://img.shields.io/github/issues-closed/johnserf-seed/tiktokdownload?style=social)](https://github.com/Johnserf-Seed/TikTokDownload)
[![F2 Downloads](https://pepy.tech/badge/f2/month)](https://pepy.tech/project/f2)
[![PyPI version](https://badge.fury.io/py/f2.svg)](https://badge.fury.io/py/f2)
[![jsDelivr monthly hits](https://data.jsdelivr.com/v1/package/gh/Johnserf-Seed/TikTokDownload/badge)](https://www.jsdelivr.com/package/gh/Johnserf-Seed/TikTokDownload)
[![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2FJohnserf-Seed%2FTikTokDownload&count_bg=%235FFFFF&title_bg=%23FB1953&icon=tiktok.svg&icon_color=%23250C1F&title=view&edge_flat=false)](https://hits.seeyoufarm.com)
[![TikHub](https://img.shields.io/badge/%E8%B5%9E%E5%8A%A9%E5%95%86-TikHub-orange?style=flat-square&logo=tiktok)](https://beta-web.tikhub.io/users/signup?referral_code=6hLcGD94)
[![Discord](https://img.shields.io/discord/1146473603450282004?color=5865F2&logo=discord&logoColor=white?style=for-the-badge)](https://discord.gg/3PhtPmgHf8)
[![Patreon](https://img.shields.io/badge/Patreon-TikTokDownload-red.svg?style=flat&logo=patreon)](https://www.patreon.com/TikTokDownload713)
</div>
## 🚀 环境准备/Environment
> [![Microsoft 应用商店](https://tvax1.sinaimg.cn/large/006908GAly1hgn87jhad8j305001qa9y.jpg)](https://aka.ms/terminal)
>
> 旧的控制台无法很好适配推荐使用Windows Terminal。
>
> [![Python v3.11.1](https://www.python.org/static/img/python-logo.png)](https://www.python.org/ftp/python/3.11.1/python-3.11.1-amd64.exe)
>
> Python3.11.1 低于该版本可能会有意外的错误
>
> [![GitHub 发行版](https://tvax2.sinaimg.cn/large/006908GAly1hh16psn51aj30a5020gly.jpg)](https://github.com/Johnserf-Seed/TikTokDownload/releases/tag/v1.4.2.2)
>
> 更新F2前的最后一个发行版下载
<details><summary> ⚙ Windows Terminal 设置(必看) </summary>
![wt配置](https://github.com/Johnserf-Seed/TikTokDownload/assets/40727745/997b6fc2-586e-4268-bee8-43bb8d68622c)
</details>
## 🧰 功能/Features
- DouYin 接口全新Abogus
- ✅ 用户信息。
- ✅ 查询用户信息。
- ✅ 下载发布作品。
- ✅ 下载收藏作品。
- ✅ 下载收藏原声。
- ✅ 下载喜欢作品。
- ✅ 下载图集作品。
- ✅ 下载短剧作品。
- ✅ 下载作品封面。
- ✅ 下载作品文案。
- ✅ 下载作品原声。
- ✅ 下载直播。
- ✅ 下载合集作品。
- ⌛ 下载关注作品。
- ✅ 关注用户信息。
- ✅ 粉丝用户信息。
- ✅ 下载好友作品。
- ✅ 下载首页推荐作品。
- ✅ 下载相关推荐作品。
- ⌛ 提取评论。
- ✅ 详细直播间信息。
- ✅ 关注用户开播状态。
- ✅ 直播间弹幕负载数据。
- ✅ 直播间弹幕采集。
- ✅ 详细用户信息。
- TikTok 接口
- ✅ 下载发布作品。
- ✅ 下载收藏作品。
- ✅ 下载喜欢作品。
- ✅ 下载图集作品。
- ✅ 下载作品封面。
- ✅ 下载作品文案。
- ✅ 下载作品原声。
- ✅ 下载播放列表。
- ✅ 下载合集作品。
- ✅ 下载搜索作品。
- ⌛ 下载关注作品。
- ⌛ 下载好友作品。
- ⌛ 下载推荐作品。
- ⌛ 下载相关推荐作品。
- ⌛ 提取评论。
- ✅ 详细直播间信息。
- ✅ 直播间开播状态。
- ⌛ 直播间弹幕发言。
- ✅ 详细用户信息。
- 更多接口,请查阅 [「F2开发者接口」](https://johnserf-seed.github.io/f2/guide/apps/douyin/)
- 异步下载
- ✅ 同时处理和下载多个作品,提高效率。
- ✅ 异步线程,减轻系统压力减少接口出错。
- ✅ 网络并发数,减少被服务器校验。
- ✅ 超时重试设置,降低采集错误率。
- Cookie
- ✅ 使用--auto-cookie自动从浏览器获取cookie。
- 接口数据模型
- ✅ 开箱即用的接口参数配置,提供完整参数生成。
- 请查阅[「使用接口模型生成XB参数」](https://johnserf-seed.github.io/f2/guide/apps/douyin/#%E4%BD%BF%E7%94%A8%E6%8E%A5%E5%8F%A3%E6%A8%A1%E5%9E%8B%E7%94%9F%E6%88%90xb%E5%8F%82%E6%95%B0-%F0%9F%9F%A2)
- 请查阅[「使用接口模型生成AB参数」](https://johnserf-seed.github.io/f2/guide/apps/douyin/#%E4%BD%BF%E7%94%A8%E6%8E%A5%E5%8F%A3%E6%A8%A1%E5%9E%8B%E7%94%9F%E6%88%90ab%E5%8F%82%E6%95%B0-%F0%9F%9F%A2)
- 接口数据过滤器
- ✅ 通过过滤接口数据,提高采集与数据处理效率。
- 请查阅[「过滤器采集数据」](https://johnserf-seed.github.io/f2/guide/apps/douyin/#%E4%BD%BF%E7%94%A8%E6%8E%A5%E5%8F%A3%E6%A8%A1%E5%9E%8B%E7%94%9F%E6%88%90xb%E5%8F%82%E6%95%B0-%F0%9F%9F%A2)
- 更多功能
- ✅ 长短链解析。
- ✅ 自定义保存目录。
- ✅ 是否下载原声。
- ✅ 是否下载封面。
- ✅ 是否下载文案。
- ✅ 单次下载作品数量。
- ✅ 单次返回作品数量。
- ✅ 自定义文件名模板。
- ✅ 代理设置。
- ✅ 指定下载时间区间。
- ✅ 提取单个/列表用户id。
- ✅ 提取单个/列表作品id。
- ✅ 提取单个/列表合集id。
- ✅ 提取单个/列表直播间rid。
- ✅ 原声json歌词转lrc歌词。
- ⌛ 设定下载作品点赞阈值。
- ⌛ 设定下载作品播放阈值。
- 更多配置文件操作,请查阅[「F2配置文件」](https://johnserf-seed.github.io/f2/site-config.html)
- 多用户配置
- ✅ 对不同用户建立不同配置与不同的下载模式。
- ✅ 灵活的cli模式方便用户快速切换配置。
- ⌛ 灵活的webui模式方便用户快速切换配置。
- 版本更新
- ✅ 全新开发 F2 依赖pip进行升级
- ✅ 自动检查 pypi 上的最新版本
- 文件检查
- ✅ 下载文件前检查文件是否已经存在,避免重复下载。
- ⌛ 添加”黑名单“,不检查这些作品是否存在。
- 命令行交互
- ✅ 提供cli模式与开发者模式
- ⌛ 提供webui模式
- ⌛ 提供本地接口转发,方便部署调用。
- 自动重命名
- ✅ 无需关心用户是否改名,从而造成重复下载。
- ⌛ 无需关心作品是否改文案,从而造成重复下载。
- 本地加密参数调用
- ✅ ABogus(dy)
- ✅ XBogus(dy、tk)
- ✅ verifyFp(dy)
- ✅ s_v_web_id(dy)
- ✅ ttwid(dy、tk)
- ✅ web_id(dy)
- ✅ _signature(dy)
- ✅ x-tt-params(tk)
- ✅ msToken(dy、tk)
- ✅ odin_tt(tk)
- ✅ device_Id(tk)
## 💡 待办/ToDo
- 创建自动化任务
- [更多请查看项目板](https://github.com/users/Johnserf-Seed/projects/1/views/1)
## 🖥 支持的操作系统/Supported Operating Systems
<details>
<summary> TikTokDownload 1.6 / F2 0.0.1.6-pw2 支持的操作系统列表 </summary>
- Windows 11
- Windows 10 版本 1809OS 内部版本 17763或更高版本
- macOS Monterey12.0)或更高版本
- macOS Big Sur11.0)或更高版本
- macOS Catalina10.15)或更高版本
- Ubuntu 20.04 LTS 或更高版本
- Debian 10 或更高版本
- CentOS 7 或更高版本
- Fedora 34 或更高版本
- Deepin (UOS) 20 或更高版本
</details>
## 📥 安装与运行/Installation and Running
1. **📦 安装/Installation**
请查阅 [「安装」](https://johnserf-seed.github.io/f2/install.html)
2. **▶️ 运行/Running**
请查阅 [「配置文件」](https://johnserf-seed.github.io/f2/install.html)
3. **🔬 测试/Test**
在 F2 安装目录打开终端运行,如果配置正确那么你不会看见报错。
```bash
python -m pytest
```
## 📸 运行过程/Running Process
<details>
<summary> 🎬 无配置文件扫码登录 </summary>
https://user-images.githubusercontent.com/40727745/fc1e6c46-d0c3-4f2a-a4a5-ca3d781e7d11
</details>
<details>
<summary> 🎬 主页作品下载 </summary>
https://user-images.githubusercontent.com/40727745/12c21d55-b629-485a-b904-54d86341c371
</details>
更多运行过程请查阅 [「F2 readme」](https://github.com/Johnserf-Seed/f2/blob/main/README.md)
## 🗂️ 项目结构/Folder
<details>
<summary>📁 目录</summary>
```bash
├─ .github
│ └─ ISSUE_TEMPLATE
│ ├── --------.md
│ └── -------.md
├─ API
│ ├── TikTokTool.txt
│ ├── user_base_info.json
│ ├── user_post_delete.json
│ ├── user_post_detail.json
│ ├── user_post_info_image.json
│ ├── user_post_info_video.json
│ └── user_profile_info.json
├─ GUI(待重构)
│ ├── Main.ui
│ ├── preview.png
│ ├── README-EN.md
│ ├── README.md
│ ├── requirements.txt
│ ├── resource.py
│ └── Resource.qrc
└─ Server
└─ algorithm
├── build-win.bat
├── package.json
├── requirements.txt
├── Server.py
├── Server.txt
├── s_v_web_id.js
├── s_v_web_id.py
├── x-bogus.js
└── x-tt-params.js
├─ .gitignore
├─ Banner.png
├─ build-win.bat
├─ Dockerfile
├─ LICENSE
├─ f2-logo.ico
├─ README-EN.md
├─ README.md
├─ requirements.txt
├─ run-server.bat
├─ run-server.sh
├─ TikTokTool.py
├─ version
└─ _config.yml
### 方式1双击启动推荐
```
双击 启动UI.vbs
```
</details>
### 方式2命令行启动
```bash
"C:\Program Files\Python311\python.exe" douyin_ui.py
```
## 💖 赞赏/Sponsor
## 📋 系统要求
<a href="https://tikhub.io/"><img style="border-radius:20px" src="https://github.com/Johnserf-Seed/f2/assets/40727745/70a67dd1-dccb-44a9-b635-c29a950f1daf"></a>
- **Python** 3.11+
- **浏览器**(可选):
- Microsoft Edge
- Google Chrome
- Mozilla Firefox
- **网络** - 能访问 www.douyin.com
[TikHub](https://tikhub.io/) 是一家提供优质数据接口服务的供应商。通过每日签到,可以获取免费额度。可以使用我的注册邀请链接:[https://beta-web.tikhub.io/users/signup?referral_code=6hLcGD94](https://beta-web.tikhub.io/users/signup?referral_code=6hLcGD94) 或 邀请码:`6hLcGD94`,注册并充值即可获得`$2`额度。
## 🎯 使用方法
[TikHub](https://tikhub.io/) 提供以下服务:
1. **粘贴链接** - 复制抖音分享链接到输入框
2. **点击下载** - 自动获取Cookie并下载
3. **完成** - 视频保存在下载目录
- 丰富的数据接口
- 每日签到免费获取额度
- 高质量的API服务
- 官网https://tikhub.io/
- 项目地址https://github.com/TikHubIO/
## 🔄 Cookie自动获取机制
程序会自动尝试以下方式获取Cookie
![赞赏](https://user-images.githubusercontent.com/40727745/217866800-23980dc1-f3ce-4bc7-b192-518651fef8da.png)
1. **Edge浏览器**(优先)
2. **Chrome浏览器**(备选)
3. **Firefox浏览器**(备选)
4. **HTTP请求**(无浏览器时)
5. **手动输入**(最后备选)
感谢对本项目的支持!如果您觉得这个项目有帮助,欢迎赞助。您可以直接访问我们的 [![Patreon](https://img.shields.io/badge/Patreon-F2-red.svg?style=flat&logo=patreon)](https://www.patreon.com/F2_pypi)
## 📦 依赖安装
首次运行会自动安装:
## 📧 联系/Contact
```bash
pip install selenium webdriver-manager requests
```
如果有任何问题或者建议,可以通过邮箱联系我:
## 🌍 环境兼容性
- 邮箱:[johnserf-seed@foxmail.com](mailto:johnserf-seed@foxmail.com)
### 有浏览器环境
- ✅ Windows 10/11 + Edge
- ✅ Windows + Chrome
- ✅ Windows + Firefox
- ✅ macOS + Chrome/Firefox
- ✅ Linux + Chrome/Firefox
### 无浏览器环境
- ✅ 服务器环境
- ✅ Docker容器
- ✅ CI/CD环境
## 🙏 鸣谢/Acknowledgments
使用HTTP请求方式获取Cookie
- [Windows Terminal](https://aka.ms/terminal)
- [Python](https://www.python.org/)
- [httpx](https://github.com/encode/httpx)
- [click](https://github.com/pallets/click)
- [aiofiles](https://github.com/Tinche/aiofiles)
- [aiosqlite](https://github.com/omnilib/aiosqlite)
- [rich](https://github.com/willmcgugan/rich)
- [qrcode](https://github.com/lincolnloop/python-qrcode)
- [pyyaml](hhttps://github.com/yaml/pyyaml)
- [jsonpath-ng](https://github.com/h2non/jsonpath-ng)
- [m3u8](https://github.com/globocom/m3u8)
- [pytest](https://github.com/pytest-dev/pytest)
## 🎨 功能说明
对于他们的贡献和努力,表示由衷的感谢。
### 下载模式
- **单个作品** - 下载单个视频
- **用户主页** - 批量下载用户发布作品
- **用户喜欢** - 下载用户点赞作品
- **用户收藏** - 下载用户收藏作品
- **直播** - 录制直播间
## ⚖️ 免责声明/Disclaimer
### 高级选项
此项目不出售、共享、加密、上传、研究任何个人信息。此项目及其相关代码仅供学习与研究使用,不构成任何明示或暗示的保证。使用者因使用此项目及其代码可能造成的任何形式的损失,作者不承担任何责任。
- **下载原声** - 保存视频背景音乐
- **下载封面** - 保存视频封面图片
- **作品数量** - 限制下载数量0=全部)
## 🔧 技术栈
## 📜 版权声明/LICENSE
- **Python 3.11** - 核心语言
- **Selenium** - 浏览器自动化
- **f2** - 抖音API库
- **tkinter** - GUI界面
- **requests** - HTTP请求
## 📝 工作原理
1. **自动Cookie**
```
Selenium启动浏览器 → 访问抖音 → 提取Cookie
HTTP请求 → 模拟浏览器 → 获取Cookie
```
2. **视频下载**
```
解析分享链接 → 调用f2库 → 请求抖音API → 获取视频URL → 下载到本地
```
## ⚠️ 注意事项
- Cookie有效期为几天过期会自动刷新
- 请勿频繁下载,避免触发风控
- 仅供学习研究使用,请尊重版权
## 📄 许可证
MIT License
Copyright (c) 2021 JohnserfSeed
## 🙏 致谢
此项目的源代码在 MIT 许可证下授权,有关详细信息,请参阅 [LICENSE](LICENSE) 文件。
- [f2](https://github.com/Johnserf-Seed/f2) - 抖音API库
- [TikTokDownload](https://github.com/Johnserf-Seed/TikTokDownload) - 原项目
## 🐛 问题反馈
## 📝 贡献者守则/CoC
如遇问题,请检查:
1. Python版本是否正确
2. 网络是否正常
3. 是否有浏览器(可选)
4. 查看日志输出的错误信息
此项目欢迎所有的贡献者。我们希望能够创建一个友好的环境,让每个人都能在尊重和理解的氛围中共同工作。在参与贡献之前,请参阅我们的 [贡献者守则](CODE_OF_CONDUCT.md)。
---
## 👨‍💻贡献者/Contributors
我们欢迎任何形式的贡献,无论是提交错误报告,提出改进意见,或者是提供代码和文档。我们都欣赏你的帮助。
![Contributors](https://contributors-img.web.app/image?repo=Johnserf-Seed/TikTokDownload)
**Made with ❤️ for Douyin users**

View File

@@ -1,11 +1,13 @@
import os
import time
import requests
COOKIE_FILE = r"C:\Users\Administrator\Desktop\TikTokDownload-main\douyin_cookie.txt"
def get_douyin_cookie_auto(force_refresh=False, headless=True):
"""
自动获取抖音访客Cookie使用Edge本地驱动
自动获取抖音访客Cookie
支持多种方式Edge、Chrome、Firefox、纯HTTP请求
"""
# 检查是否已有Cookie且不需要强制刷新
@@ -21,58 +23,84 @@ def get_douyin_cookie_auto(force_refresh=False, headless=True):
print("[自动Cookie] 开始自动获取...")
# 方法1: 尝试使用Selenium支持Edge/Chrome/Firefox
cookie = try_selenium_cookie(headless)
if cookie:
return cookie
# 方法2: 纯HTTP请求方式不依赖浏览器
print("[自动Cookie] Selenium不可用尝试HTTP请求方式...")
cookie = try_http_cookie()
if cookie:
return cookie
print("[自动Cookie] 错误: 所有自动获取方式都失败")
print("[自动Cookie] 提示: 请手动获取Cookie")
return None
def try_selenium_cookie(headless=True):
"""尝试使用Selenium获取Cookie支持Edge/Chrome/Firefox"""
try:
# 尝试使用selenium with本地Edge
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.edge.service import Service as EdgeService
print("[自动Cookie] 启动Edge浏览器...")
driver = None
options = EdgeOptions()
if headless:
print("[自动Cookie] 使用无头模式...")
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)
# 尝试使用系统Edge驱动
# 尝试Edge
try:
# 方法1: 直接使用Edge自动查找驱动
from selenium.webdriver.edge.options import Options as EdgeOptions
print("[自动Cookie] 尝试启动Edge浏览器...")
options = EdgeOptions()
if headless:
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Edge(options=options)
print("[自动Cookie] Edge浏览器启动成功(自动驱动)")
except Exception as e1:
print(f"[自动Cookie] 自动驱动失败: {e1}")
print("[自动Cookie] Edge浏览器启动成功")
# 方法2: 尝试常见驱动路径
common_paths = [
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe",
r"C:\Program Files\Microsoft\Edge\Application\msedgedriver.exe",
os.path.expandvars(r"%PROGRAMFILES%\Microsoft\Edge\Application\msedgedriver.exe"),
os.path.expandvars(r"%PROGRAMFILES(X86)%\Microsoft\Edge\Application\msedgedriver.exe"),
]
except Exception as e:
print(f"[自动Cookie] Edge失败: {str(e)[:50]}")
driver = None
for driver_path in common_paths:
if os.path.exists(driver_path):
print(f"[自动Cookie] 尝试使用驱动: {driver_path}")
try:
service = EdgeService(executable_path=driver_path)
driver = webdriver.Edge(service=service, options=options)
print("[自动Cookie] Edge浏览器启动成功指定驱动")
break
except Exception as e2:
print(f"[自动Cookie] 驱动 {driver_path} 失败: {e2}")
continue
if driver is None:
raise Exception("无法找到可用的Edge驱动")
# 尝试Chrome
try:
from selenium.webdriver.chrome.options import Options as ChromeOptions
print("[自动Cookie] 尝试启动Chrome浏览器...")
options = ChromeOptions()
if headless:
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
print("[自动Cookie] Chrome浏览器启动成功")
except Exception as e2:
print(f"[自动Cookie] Chrome失败: {str(e2)[:50]}")
# 尝试Firefox
try:
from selenium.webdriver.firefox.options import Options as FirefoxOptions
print("[自动Cookie] 尝试启动Firefox浏览器...")
options = FirefoxOptions()
if headless:
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
print("[自动Cookie] Firefox浏览器启动成功")
except Exception as e3:
print(f"[自动Cookie] Firefox失败: {str(e3)[:50]}")
if driver is None:
return None
# 访问抖音
print("[自动Cookie] 访问抖音网站...")
@@ -93,7 +121,6 @@ def get_douyin_cookie_auto(force_refresh=False, headless=True):
cookie_str = "; ".join([f"{c['name']}={c['value']}" for c in cookies])
print(f"[自动Cookie] 成功获取 {len(cookies)} 个Cookie项")
print(f"[自动Cookie] Cookie项: {', '.join([c['name'] for c in cookies])}")
print(f"[自动Cookie] Cookie长度: {len(cookie_str)}")
# 保存
@@ -107,25 +134,90 @@ def get_douyin_cookie_auto(force_refresh=False, headless=True):
driver.quit()
return cookie_str
except ImportError as e:
print(f"[自动Cookie] 错误: selenium未安装 - {e}")
print("[自动Cookie] 提示: 请运行 pip install selenium")
except ImportError:
print("[自动Cookie] Selenium未安装,跳过浏览器方式")
return None
except Exception as e:
print(f"[自动Cookie] 错误: {e}")
import traceback
traceback.print_exc()
print(f"[自动Cookie] Selenium方式失败: {e}")
return None
def try_http_cookie():
"""使用纯HTTP请求获取Cookie不依赖浏览器"""
try:
print("[自动Cookie] 使用HTTP请求方式...")
session = requests.Session()
# 模拟正常浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
}
session.headers.update(headers)
# 访问抖音首页
print("[自动Cookie] 访问抖音首页...")
resp = session.get("https://www.douyin.com", timeout=15)
print(f"[自动Cookie] 响应状态: {resp.status_code}")
# 提取Cookie
cookies = session.cookies.get_dict()
if cookies:
# 转换为字符串
cookie_str = "; ".join([f"{name}={value}" for name, value in cookies.items()])
print(f"[自动Cookie] 成功获取 {len(cookies)} 个Cookie项")
print(f"[自动Cookie] Cookie项: {', '.join(cookies.keys())}")
print(f"[自动Cookie] Cookie长度: {len(cookie_str)}")
# 保存
try:
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
f.write(cookie_str)
print(f"[自动Cookie] Cookie已保存")
except Exception as e:
print(f"[自动Cookie] 保存失败: {e}")
return cookie_str
else:
print("[自动Cookie] HTTP方式未获取到Cookie")
return None
except requests.exceptions.Timeout:
print("[自动Cookie] HTTP请求超时")
return None
except requests.exceptions.ConnectionError:
print("[自动Cookie] 网络连接失败")
return None
except Exception as e:
print(f"[自动Cookie] HTTP方式失败: {e}")
return None
if __name__ == "__main__":
print("="*60)
print("测试自动获取CookieEdge本地驱动")
print("测试自动获取Cookie多浏览器+HTTP方式")
print("="*60)
cookie = get_douyin_cookie_auto(force_refresh=True, headless=False)
cookie = get_douyin_cookie_auto(force_refresh=True, headless=True)
if cookie:
print(f"\n成功Cookie长度: {len(cookie)}")
print(f"Cookie前200字符:\n{cookie[:200]}...")
else:
print("\n失败无法获取Cookie")
print("\n失败:无法自动获取Cookie")
print("\n请手动获取Cookie")
print("1. 打开浏览器访问 www.douyin.com")
print("2. 按F12打开开发者工具")
print("3. 刷新页面点击Network标签")
print("4. 点击任意请求复制Cookie值")