抖音长截图服务使用说明
Posted on Mon 15 January 2024 in 技术
本文介绍基于 Playwright 封装的抖音长截图服务,涵盖能力范围、接口设计、使用范例以及性能调优建议,便于快速集成到现有业务系统中。
服务概述
核心功能已经封装在 app/services/playwright_service.py 中,经过大量测试验证,推荐使用的默认参数如下:
- 滚动距离:1000 px
- 底部裁剪:300 px
- 平均截图数量:4–5 张
- 平均文件大小:2–4 MB
GitHub 仓库:https://github.com/heyaohua/douyin_screenshot_service
核心能力
- 移动端模拟:完整模拟 iPhone 设备视口与 UA
- 智能滚动:自动识别内部滚动容器并控制节奏
- 懒加载处理:触发页面动态内容渲染
- 图像拼接:裁剪重叠区域,生成无缝长图
- 错误处理:封装异常重试、日志与超时机制
主要接口
take_long_screenshot(url, output_dir="screenshots")
url:待截图抖音页面 URLoutput_dir:输出目录(默认screenshots)
返回值示例:
{
"success": True,
"output_path": "screenshots/douyin_long_screenshot_20250916_135333.png",
"screenshot_count": 4,
"total_height": 9228,
"file_size": 2764800,
"original_url": "https://v.douyin.com/...",
"current_url": "https://haohuo.jinritemai.com/...",
"title": "页面标题"
}
HTTP API 设计
长截图接口
- 请求:
POST /douyin/long-screenshot - 请求体:
{
"url": "https://v.douyin.com/Zdo3P7Zv51o/"
}
- 响应:
{
"message": "长截图完成",
"data": {
"success": true,
"output_path": "screenshots/douyin_long_screenshot_20250916_135333.png",
"screenshot_count": 4,
"total_height": 9228,
"file_size": 2764800
}
}
测试接口
- 请求:
POST /douyin/test-long-screenshot - 说明:使用预设 URL 触发一次完整流程,便于巡检。
使用示例
服务内调用
from app.services.playwright_service import playwright_service
async def example():
await playwright_service.initialize()
result = await playwright_service.take_long_screenshot(
url="https://v.douyin.com/Zdo3P7Zv51o/",
output_dir="screenshots"
)
if result["success"]:
print(f"截图完成: {result['output_path']}")
print(f"截图数量: {result['screenshot_count']}")
print(f"总高度: {result['total_height']}px")
await playwright_service.close()
HTTP API 调用
curl -X POST "http://localhost:8000/douyin/long-screenshot" \
-H "Content-Type: application/json" \
-d '{"url": "https://v.douyin.com/Zdo3P7Zv51o/"}'
curl -X POST "http://localhost:8000/douyin/test-long-screenshot"
本地测试脚本
cd tests
python test_service.py
性能指标
| 滚动距离 | 截图数量 | 平均文件大小 | 效率评估 |
|---|---|---|---|
| 1000 px | 4–5 张 | 2.6–3.7 MB | ⭐⭐⭐⭐⭐ 推荐参数 |
| 900 px | 6 张 | 4.6 MB | ⭐⭐⭐⭐ |
| 800 px | 6 张 | 4.3 MB | ⭐⭐⭐ |
| 700 px | 7 张 | 5.0 MB | ⭐⭐ |
| 600 px | 8 张 | 5.7 MB | ⭐ |
目录结构
app/services/
├── playwright_service.py # 主服务入口
│ ├── take_long_screenshot # 长截图方法
│ └── _stitch_screenshots # 图片拼接方法
app/api/
├── douyin.py # HTTP API 定义
│ ├── /long-screenshot # 长截图接口
│ └── /test-long-screenshot # 测试接口
tests/
├── test_service.py # 集成测试脚本
└── simple_douyin_test.py # 快速验证脚本
运维与实践建议
- 生命周期管理:调用前需执行
initialize(),结束后务必调用close()释放浏览器资源。 - 目录权限:确保输出目录具备写权限,并定期清理历史截图。
- 错误兜底:检查返回的
success字段并结合日志定位问题。 - 并发控制:视负载设置队列或限流,避免同时创建大量浏览器实例。
- 监控告警:建议将成功率、耗时、文件大小等指标纳入监控系统。
日志样例
2025-09-16 13:53:33,832 - INFO - 拼接图片尺寸: 1170 x 9228
2025-09-16 13:53:35,160 - INFO - ✅ 成功: True
2025-09-16 13:53:35,160 - INFO - 📊 截图数量: 4
2025-09-16 13:53:35,160 - INFO - 💾 文件大小: 2.64MB
成功案例
- URL:
https://v.douyin.com/Zdo3P7Zv51o/ - 截图数量:4 张
- 总高度:9228 px
- 文件大小:2.64 MB
- 处理时长:约 22 秒
- 成功率:100%
如需深入定制或扩展能力,请参考仓库中的完整代码与测试用例。