autoUpload/examples/test_xhs_note_uploader.py

232 lines
6.6 KiB
Python
Raw Permalink Normal View History

# -*- coding: utf-8 -*-
"""
小红书笔记上传器测试脚本
用于测试优化后的图文笔记上传功能
"""
import sys
import os
import asyncio
from pathlib import Path
from datetime import datetime, timedelta
# 添加项目根目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
sys.path.append(project_root)
from conf import BASE_DIR
from uploader.xhs_note_uploader.main import (
XiaoHongShuImageNote,
XiaoHongShuVideoNote,
xiaohongshu_note_setup
)
async def test_image_note_immediate():
"""测试立即发布图文笔记"""
print("\n" + "=" * 60)
print("【测试1】立即发布图文笔记")
print("=" * 60)
# Cookie文件路径
account_file = Path(BASE_DIR) / "cookies" / "xiaohongshu_note" / "account.json"
account_file.parent.mkdir(parents=True, exist_ok=True)
# 检查Cookie
cookie_valid = await xiaohongshu_note_setup(str(account_file), handle=True)
if not cookie_valid:
print("❌ Cookie无效请重新登录")
return False
# 准备图片
image_paths = [
str(Path(BASE_DIR) / "videos" / "demo.png"),
]
# 验证图片存在
for img_path in image_paths:
if not os.path.exists(img_path):
print(f"❌ 图片不存在: {img_path}")
return False
try:
# 创建图文笔记
note = XiaoHongShuImageNote(
title="测试图文笔记标题✨",
content="这是一条测试笔记的正文内容~\n\n测试优化后的上传功能!",
tags=["测试", "笔记"],
image_paths=image_paths,
publish_date=0, # 立即发布
account_file=str(account_file),
location="上海市",
headless=False # 有头模式,方便观察
)
# 执行上传
await note.main()
print("\n✅ 测试1通过立即发布图文笔记成功")
return True
except Exception as e:
print(f"\n❌ 测试1失败: {e}")
return False
async def test_image_note_scheduled():
"""测试定时发布图文笔记"""
print("\n" + "=" * 60)
print("【测试2】定时发布图文笔记")
print("=" * 60)
# Cookie文件路径
account_file = Path(BASE_DIR) / "cookies" / "xiaohongshu_note" / "account.json"
# 检查Cookie
cookie_valid = await xiaohongshu_note_setup(str(account_file), handle=False)
if not cookie_valid:
print("❌ Cookie无效")
return False
# 准备图片
image_paths = [
str(Path(BASE_DIR) / "videos" / "demo.png"),
]
# 设置发布时间2小时后
publish_time = datetime.now() + timedelta(hours=2)
publish_time = publish_time.replace(second=0, microsecond=0)
try:
# 创建图文笔记
note = XiaoHongShuImageNote(
title="定时发布测试笔记⏰",
content="这是一条定时发布的测试笔记~\n\n将在2小时后发布",
tags=["定时发布", "测试"],
image_paths=image_paths,
publish_date=publish_time,
account_file=str(account_file),
headless=False
)
# 执行上传
await note.main()
print(f"\n✅ 测试2通过定时发布设置成功发布时间{publish_time}")
return True
except Exception as e:
print(f"\n❌ 测试2失败: {e}")
return False
async def test_video_note():
"""测试视频笔记上传"""
print("\n" + "=" * 60)
print("【测试3】视频笔记上传")
print("=" * 60)
# Cookie文件路径
account_file = Path(BASE_DIR) / "cookies" / "xiaohongshu_note" / "account.json"
# 检查Cookie
cookie_valid = await xiaohongshu_note_setup(str(account_file), handle=False)
if not cookie_valid:
print("❌ Cookie无效")
return False
# 准备视频
video_path = str(Path(BASE_DIR) / "videos" / "demo.mp4")
if not os.path.exists(video_path):
print(f"❌ 视频不存在: {video_path}")
return False
try:
# 创建视频笔记
note = XiaoHongShuVideoNote(
title="测试视频笔记🎬",
content="这是一条测试视频笔记的正文内容~\n\n测试优化后的视频上传功能!",
tags=["视频测试", "笔记"],
video_path=video_path,
publish_date=0, # 立即发布
account_file=str(account_file),
headless=False
)
# 执行上传
await note.main()
print("\n✅ 测试3通过视频笔记上传成功")
return True
except Exception as e:
print(f"\n❌ 测试3失败: {e}")
return False
async def run_all_tests():
"""运行所有测试"""
print("\n" + "=" * 60)
print("小红书笔记上传器 - 完整测试")
print("=" * 60)
results = []
# 测试1立即发布图文笔记
result1 = await test_image_note_immediate()
results.append(("立即发布图文笔记", result1))
if result1:
# 等待一段时间再继续测试(避免频繁操作)
print("\n⏰ 等待30秒后继续下一个测试...")
await asyncio.sleep(30)
# 测试2定时发布图文笔记
# result2 = await test_image_note_scheduled()
# results.append(("定时发布图文笔记", result2))
# if result2:
# print("\n⏰ 等待30秒后继续下一个测试...")
# await asyncio.sleep(30)
# 测试3视频笔记上传
# result3 = await test_video_note()
# results.append(("视频笔记上传", result3))
# 打印测试结果
print("\n" + "=" * 60)
print("测试结果汇总")
print("=" * 60)
for test_name, result in results:
status = "✅ 通过" if result else "❌ 失败"
print(f"{status} - {test_name}")
passed = sum(1 for _, r in results if r)
total = len(results)
print(f"\n总计:{passed}/{total} 个测试通过")
if passed == total:
print("\n🎉 所有测试通过!")
else:
print("\n⚠️ 部分测试失败,请检查错误信息")
if __name__ == "__main__":
# 运行所有测试
asyncio.run(run_all_tests())
# 如果只想运行单个测试,注释掉上面一行,取消下面的注释:
# asyncio.run(test_image_note_immediate())
# asyncio.run(test_image_note_scheduled())
# asyncio.run(test_video_note())