之前取的是本任务已有作品里**最早**的那条 —— 既不是主页上看到的第一条, 也只看得到被监控的那批链接。现在采集时对每个博主额外问一次作品列表 (倒序,只要第一条),把它的发布时间落进账号快照;矩阵优先用它,没问到 时退回库里最新的一条作品。 - 作品模式:每个博主每轮一次请求,同轮内去重;连接超时重试一次。 - 博主模式:本来就在拉作品列表,直接用其中的最新时间。 - 新列 monitor_creator_stat.latest_published_at(毫秒,可空)。
457 lines
18 KiB
Python
457 lines
18 KiB
Python
# -*- coding: utf-8 -*-
|
||
# Copyright (c) 2025 [email protected]
|
||
#
|
||
# This file is part of MediaCrawler project.
|
||
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/monitor/douyin_fetch.py
|
||
# GitHub: https://github.com/NanmiCoder
|
||
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
|
||
#
|
||
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
|
||
# 1. 不得用于任何商业用途。
|
||
# 2. 使用时应遵守对应平台的使用条款和robots.txt规则。
|
||
# 3. 不得进行大规模爬取或对平台造成运营干扰。
|
||
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
|
||
# 5. 不得用于任何非法或不当的用途。
|
||
#
|
||
# 详细许可条款请参阅项目根目录下的LICENSE文件。
|
||
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
|
||
|
||
"""抖音采集:直接走 Web 接口,不起爬虫子进程。
|
||
|
||
与 ``media_platform/douyin`` 那条路的分工:
|
||
|
||
* 那边起一个 Playwright 子进程、构造一大串**自相矛盾的浏览器指纹参数**(参数说自己是
|
||
Mac + Chrome 125,UA 说自己是 Linux + Chrome 155),网关回一个 200 + 空 body,
|
||
然后被翻译成 ``Exception("account blocked")`` —— 看起来像账号被封,其实什么都不是。
|
||
* 这边不起子进程、只发必要参数,用浏览器里那份登录态。见 ``douyin_api``。
|
||
|
||
采到的东西写成 ``store/douyin`` 那套 jsonl 形状,所以 **ingest 完全不知道数据是怎么来的**
|
||
—— 重采样、差分、事件、通知、报表全都照旧。
|
||
"""
|
||
|
||
import asyncio
|
||
import json
|
||
from datetime import datetime
|
||
|
||
import httpx
|
||
from pathlib import Path
|
||
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
||
|
||
from tools import utils
|
||
|
||
from . import adapters, douyin_api
|
||
from .models import MODE_CREATOR, MODE_NOTE, MonitorTask
|
||
|
||
# 拉多少条作品。接口单页上限就是 20,要多了也没用。
|
||
DEFAULT_VIDEO_LIMIT = 20
|
||
|
||
|
||
async def collect(
|
||
out_dir: Path,
|
||
*,
|
||
platform: str,
|
||
mode: str,
|
||
limit: int,
|
||
want_comments: bool,
|
||
comment_limit: int,
|
||
targets: Sequence[Any],
|
||
known_aweme_ids: Iterable[str] = (),
|
||
cookie: str = "",
|
||
identities: Sequence[Any] = (),
|
||
concurrency: int = 1,
|
||
switch_delay_seconds: float = 0.0,
|
||
) -> Dict[str, Any]:
|
||
"""跑一轮抖音采集,把产物写进 ``out_dir`` 下 store 那个目录里。
|
||
|
||
参数是散的、不收 ORM 对象:调用方那边 ``task`` 在会话关掉之后就 detached 了,
|
||
传对象进来迟早会踩到「属性已过期」。
|
||
|
||
``identities`` 非空时进入**身份池模式**:目标按 Rendezvous Hashing 分给各个身份,
|
||
逐个分片执行。默认串行 —— 同一个出口 IP 上并发多个 cookie 比单账号高频更可疑;
|
||
``concurrency`` 只是留了个口子,有独立出口 IP 之前别调大。
|
||
|
||
**不抛异常**:失败也把(可能为空的)产物落下去,并把原因放进 ``errors`` 交给调用方。
|
||
让调用方去决定这是「一轮正常但没数据」还是「一轮失败」—— 这个判断不该藏在这里。
|
||
"""
|
||
notes: List[Dict[str, Any]] = []
|
||
comments: List[Dict[str, Any]] = []
|
||
# 博主**账号级**指标(粉丝 / 总获赞 / 作品数)。作品列表之外单独要一次,
|
||
# 只有博主模式才有 —— 作品模式的目标是一件作品,没有"这个博主是谁"可问。
|
||
profiles: List[Dict[str, Any]] = []
|
||
errors: List[str] = []
|
||
shards: List[Dict[str, Any]] = []
|
||
|
||
# **整个 collect 只去重一次的、跨目标的集合**:退化路径会把「库里已知的全部作品」
|
||
# 在每个目标下都刷一遍,多个目标就会出现同一件作品好几条记录 —— 而一对一快照的
|
||
# 唯一键是 (task_id, note_id, run_id),同一条作品在一轮里出现两次会直接撞键。
|
||
seen_aweme: set = set()
|
||
|
||
if identities:
|
||
from . import identities as identity_pool
|
||
|
||
plan = identity_pool.assign(targets, [item.identity_key for item in identities])
|
||
batches = [
|
||
(item, plan[item.identity_key])
|
||
for item in identities
|
||
if plan[item.identity_key]
|
||
]
|
||
|
||
async def run_batch(identity, shard):
|
||
return await _collect_batch(
|
||
shard,
|
||
identity=identity,
|
||
mode=mode,
|
||
limit=limit,
|
||
want_comments=want_comments,
|
||
comment_limit=comment_limit,
|
||
cookie=cookie,
|
||
known_aweme_ids=known_aweme_ids,
|
||
seen_aweme=seen_aweme,
|
||
)
|
||
|
||
if concurrency > 1 and len(batches) > 1:
|
||
results = await asyncio.gather(*(run_batch(i, s) for i, s in batches))
|
||
else:
|
||
results = []
|
||
for index, (identity, shard) in enumerate(batches):
|
||
results.append(await run_batch(identity, shard))
|
||
# 换账号之间留一点空档:连续在同一个 IP 上换登录态更像异常流量。
|
||
if index < len(batches) - 1 and switch_delay_seconds > 0:
|
||
await asyncio.sleep(switch_delay_seconds)
|
||
|
||
for (identity, shard), result in zip(batches, results):
|
||
notes.extend(result["notes"])
|
||
comments.extend(result["comments"])
|
||
profiles.extend(result["profiles"])
|
||
errors.extend(result["errors"])
|
||
shards.append(
|
||
{
|
||
"key": identity.identity_key,
|
||
"targets": result["targets"],
|
||
"notes": len(result["notes"]),
|
||
"comments": len(result["comments"]),
|
||
"errors": list(result["errors"]),
|
||
}
|
||
)
|
||
else:
|
||
result = await _collect_batch(
|
||
targets,
|
||
identity=None,
|
||
mode=mode,
|
||
limit=limit,
|
||
want_comments=want_comments,
|
||
comment_limit=comment_limit,
|
||
cookie=cookie,
|
||
known_aweme_ids=known_aweme_ids,
|
||
seen_aweme=seen_aweme,
|
||
)
|
||
notes.extend(result["notes"])
|
||
comments.extend(result["comments"])
|
||
profiles.extend(result["profiles"])
|
||
errors.extend(result["errors"])
|
||
|
||
# 并发跑分片时,两个分片可能各自刷新到同一件已知作品 —— 落盘前去一次重,
|
||
# 否则唯一键 (task_id, note_id, run_id) 会撞。
|
||
deduped: List[Dict[str, Any]] = []
|
||
seen_note_ids: set = set()
|
||
for note in notes:
|
||
note_id = note.get("aweme_id")
|
||
if note_id and note_id in seen_note_ids:
|
||
continue
|
||
if note_id:
|
||
seen_note_ids.add(note_id)
|
||
deduped.append(note)
|
||
|
||
jsonl_dir = _write_artifacts(out_dir, platform, mode, deduped, comments, profiles)
|
||
return {
|
||
"notes": len(deduped),
|
||
"comments": len(comments),
|
||
"errors": errors,
|
||
"jsonl_dir": str(jsonl_dir),
|
||
"shards": shards,
|
||
}
|
||
|
||
|
||
async def _collect_batch(
|
||
targets: Sequence[Any],
|
||
*,
|
||
identity: Any,
|
||
mode: str,
|
||
limit: int,
|
||
want_comments: bool,
|
||
comment_limit: int,
|
||
cookie: str,
|
||
known_aweme_ids: Iterable[str],
|
||
seen_aweme: set,
|
||
) -> Dict[str, Any]:
|
||
"""一个身份负责的那一片目标。错误只往自己的列表里记,由调用方合并。"""
|
||
notes: List[Dict[str, Any]] = []
|
||
comments: List[Dict[str, Any]] = []
|
||
profiles: List[Dict[str, Any]] = []
|
||
errors: List[str] = []
|
||
|
||
for target in targets:
|
||
external_id = target.external_id
|
||
|
||
# 两种模式的目标是不同的东西,不能走同一条路:
|
||
# 作品模式 —— 目标本身就是作品 id,直接取详情(**这个接口没被挡,今天就能用**)。
|
||
# 博主模式 —— 目标是主页 sec_uid,要先拉作品列表;那个接口被真校验挡着,退化到
|
||
# 刷新库里已知的作品(新作品发现不了)。
|
||
if mode == MODE_NOTE:
|
||
try:
|
||
videos = [
|
||
await douyin_api.video_detail(
|
||
external_id, cookie=cookie, identity=identity
|
||
)
|
||
]
|
||
except douyin_api.DouyinApiError as exc:
|
||
errors.append(f"拉取作品 {external_id} 失败:{exc}")
|
||
videos = []
|
||
# 作品详情里带着作者的粉丝/总获赞。作品模式**不会**单独问博主资料 ——
|
||
# 不从这里收一份,这类任务(超级编导导入的都在这里)的博主粉丝数永远是空的。
|
||
#
|
||
# 顺带问一次这个博主**主页上最新的视频**:它可能根本不在监控目标里(自然发的、
|
||
# 别的活动发的),但「他最近还发不发」只能从主页看。同一轮里一个博主只问一次。
|
||
latest_by_creator: Dict[str, Optional[int]] = {}
|
||
for video in videos:
|
||
profile = _profile_from_author(video)
|
||
creator_id = str(video.get("creator_id") or "")
|
||
latest: Optional[int] = None
|
||
if creator_id:
|
||
if creator_id not in latest_by_creator:
|
||
latest_by_creator[creator_id] = await _latest_video_at(
|
||
creator_id, cookie, identity
|
||
)
|
||
latest = latest_by_creator[creator_id]
|
||
|
||
if profile is None:
|
||
if latest is None:
|
||
continue
|
||
# 账号指标一个都没拿到,但知道了最新视频时间 —— 也值得落一条快照,
|
||
# 否则矩阵上这个号的「最新视频」永远是空的。
|
||
profile = {
|
||
"creator_hash": str(video.get("creator_hash") or ""),
|
||
"creator_id": creator_id,
|
||
"nickname": str(video.get("nickname") or ""),
|
||
"fans": None,
|
||
"total_favorited": None,
|
||
"works": None,
|
||
"following": None,
|
||
}
|
||
profile["latest_published_at"] = latest
|
||
profiles.append(profile)
|
||
else:
|
||
videos = await _creator_works(
|
||
external_id,
|
||
limit,
|
||
known_aweme_ids,
|
||
seen_aweme,
|
||
cookie,
|
||
errors,
|
||
identity,
|
||
)
|
||
profile = await _creator_profile(
|
||
external_id, videos, cookie, errors, identity
|
||
)
|
||
if profile is not None:
|
||
profiles.append(profile)
|
||
|
||
for video in videos:
|
||
aweme_id = video.get("aweme_id")
|
||
if not aweme_id or aweme_id in seen_aweme:
|
||
continue
|
||
seen_aweme.add(aweme_id)
|
||
notes.append(video)
|
||
|
||
if want_comments:
|
||
try:
|
||
comments.extend(
|
||
await douyin_api.video_comments(
|
||
aweme_id,
|
||
count=comment_limit,
|
||
cookie=cookie,
|
||
identity=identity,
|
||
)
|
||
)
|
||
except douyin_api.DouyinApiError as exc:
|
||
errors.append(f"拉取作品 {aweme_id} 的评论失败:{exc}")
|
||
|
||
return {
|
||
"notes": notes,
|
||
"comments": comments,
|
||
"profiles": profiles,
|
||
"errors": errors,
|
||
"targets": len(targets),
|
||
}
|
||
|
||
|
||
def _profile_from_author(video: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||
"""把作品详情里那份 author 拼成一条账号快照;什么都不全就返回 None。
|
||
|
||
只在**有值**时收:author 对象偶尔是精简版(只有 uid/nickname),那种情况下写一条
|
||
全 NULL 的快照没有意义,还会让界面显示「采集时间有、数字没有」。
|
||
"""
|
||
creator_hash = str(video.get("creator_hash") or "")
|
||
if not creator_hash:
|
||
return None
|
||
|
||
stats = (
|
||
video.get("creator_fans"),
|
||
video.get("creator_total_favorited"),
|
||
video.get("creator_works"),
|
||
video.get("creator_following"),
|
||
)
|
||
if all(value is None for value in stats):
|
||
return None
|
||
|
||
return {
|
||
"creator_hash": creator_hash,
|
||
"creator_id": str(video.get("creator_id") or ""),
|
||
"nickname": str(video.get("nickname") or ""),
|
||
"fans": video.get("creator_fans"),
|
||
"total_favorited": video.get("creator_total_favorited"),
|
||
"works": video.get("creator_works"),
|
||
"following": video.get("creator_following"),
|
||
}
|
||
|
||
|
||
async def _latest_video_at(
|
||
sec_user_id: str, cookie: str, identity: Any = None
|
||
) -> Optional[int]:
|
||
"""博主主页第一条(最新)视频的发布时间(毫秒);拿不到返回 None。
|
||
|
||
作品列表按发布时间倒序,只要最新那条,所以一次请求就够,不翻页。连接超时重试一次
|
||
(容器到抖音的 TCP 连接偶尔会卡);其它错误直接放弃 —— 这是附加信息,不值得为一轮
|
||
采集增加更多失败面。
|
||
"""
|
||
if not sec_user_id:
|
||
return None
|
||
try:
|
||
videos = await douyin_api.author_videos(
|
||
sec_user_id, count=1, cookie=cookie, identity=identity
|
||
)
|
||
except httpx.TransportError:
|
||
await asyncio.sleep(1.0)
|
||
try:
|
||
videos = await douyin_api.author_videos(
|
||
sec_user_id, count=1, cookie=cookie, identity=identity
|
||
)
|
||
except Exception: # noqa: BLE001 - 附加信息,失败就留空
|
||
return None
|
||
except Exception: # noqa: BLE001
|
||
return None
|
||
|
||
stamps = [adapters.DY.to_ms(video.get("create_time")) for video in videos]
|
||
stamps = [stamp for stamp in stamps if stamp]
|
||
return max(stamps) if stamps else None
|
||
|
||
|
||
async def _creator_profile(
|
||
sec_user_id: str,
|
||
videos: Sequence[Dict[str, Any]],
|
||
cookie: str,
|
||
errors: List[str],
|
||
identity: Any = None,
|
||
) -> Optional[Dict[str, Any]]:
|
||
"""问一次博主的账号级指标。拿不到就算了 —— **不能因为顺手的附加信息失败,
|
||
就把这一轮本来采到的作品也判成失败。**
|
||
|
||
creator_hash 优先取作品自带的那个:作品是靠 ``anonymize_user_id(author.uid)`` 得到
|
||
哈希的,而快照表和作品必须对得上号,否则界面上永远查不出这个博主的粉丝数。只有当一件
|
||
作品都没采到时(列表被挡且没有已知作品可刷新),才退回资料接口自己算的哈希 ——
|
||
那种情况下也只剩它了。
|
||
"""
|
||
try:
|
||
profile = await douyin_api.author_profile(
|
||
sec_user_id, cookie=cookie, identity=identity
|
||
)
|
||
except douyin_api.DouyinApiError as exc:
|
||
errors.append(f"拉取博主 {sec_user_id} 的资料失败:{exc}")
|
||
return None
|
||
|
||
if videos:
|
||
profile["creator_hash"] = videos[0].get("creator_hash") or profile["creator_hash"]
|
||
# 作品列表是倒序的,最早取到的这 N 条里最新的那条就是主页第一条。
|
||
stamps = [adapters.DY.to_ms(video.get("create_time")) for video in videos]
|
||
stamps = [stamp for stamp in stamps if stamp]
|
||
if stamps:
|
||
profile["latest_published_at"] = max(stamps)
|
||
if not profile.get("creator_hash"):
|
||
# 哈希都算不出来的快照没人能查到,落下去只是垃圾。
|
||
errors.append(f"博主 {sec_user_id} 的资料里没有可用的身份标识,跳过账号指标")
|
||
return None
|
||
return profile
|
||
|
||
|
||
async def _creator_works(
|
||
sec_user_id: str,
|
||
limit: int,
|
||
known_aweme_ids: Iterable[str],
|
||
seen_aweme: set,
|
||
cookie: str,
|
||
errors: List[str],
|
||
identity: Any = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""一个博主的作品:先要列表,列表被挡时退化成刷新已知作品。
|
||
|
||
作品列表(``aweme/post``)被抖音单独加了真校验 —— 不带 ``x-tt-argus`` 回 403,
|
||
带上 dummy 值回 200 + 空 body。所以这里拿不到**新**作品,只能保住已知的。
|
||
"""
|
||
try:
|
||
return await douyin_api.author_videos(
|
||
sec_user_id, count=limit, cookie=cookie, identity=identity
|
||
)
|
||
except douyin_api.DouyinApiError as exc:
|
||
errors.append(f"拉取博主 {sec_user_id} 的作品列表失败:{exc}")
|
||
|
||
refreshed: List[Dict[str, Any]] = []
|
||
for aweme_id in known_aweme_ids:
|
||
if aweme_id in seen_aweme:
|
||
continue
|
||
try:
|
||
refreshed.append(
|
||
await douyin_api.video_detail(
|
||
aweme_id, cookie=cookie, identity=identity
|
||
)
|
||
)
|
||
except douyin_api.DouyinApiError as detail_exc:
|
||
errors.append(f"刷新作品 {aweme_id} 失败:{detail_exc}")
|
||
return refreshed
|
||
|
||
|
||
def _write_artifacts(
|
||
out_dir: Path,
|
||
platform: str,
|
||
mode: str,
|
||
notes: List[Dict[str, Any]],
|
||
comments: List[Dict[str, Any]],
|
||
profiles: Sequence[Dict[str, Any]] = (),
|
||
) -> Path:
|
||
"""按爬虫那套目录与文件名写 jsonl。
|
||
|
||
目录名取 ``adapters.artifact_dir``(抖音是 ``douyin``,而不是平台 id ``dy``)——
|
||
和 ingest 找文件用的是同一个来源,两边不会走散。
|
||
"""
|
||
jsonl_dir = out_dir / adapters.artifact_dir(platform) / "jsonl"
|
||
jsonl_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
kind = "creator" if mode == MODE_CREATOR else "detail"
|
||
date = datetime.now().strftime("%Y-%m-%d")
|
||
|
||
_write_jsonl(jsonl_dir / f"{kind}_contents_{date}.jsonl", notes)
|
||
# 评论文件即使没有评论也建出来:ingest 靠「文件在不在」区分「这一轮没评论」和
|
||
# 「这一轮什么都没抓到」,两种情况的含义完全不同。
|
||
_write_jsonl(jsonl_dir / f"{kind}_comments_{date}.jsonl", comments)
|
||
# 博主资料同样无条件写:空文件表示"问了但没问到",没有文件表示"这次根本没问"
|
||
# (作品模式)。两者在 ingest 那边走的是同一条路(都不落快照),但留空文件能让
|
||
# 事后翻 run 目录时看出到底问没问过。
|
||
_write_jsonl(jsonl_dir / f"{kind}_profile_{date}.jsonl", list(profiles))
|
||
return jsonl_dir
|
||
|
||
|
||
def _write_jsonl(path: Path, records: List[Dict[str, Any]]) -> None:
|
||
with path.open("w", encoding="utf-8") as handle:
|
||
for record in records:
|
||
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||
utils.logger.info(f"[douyin_fetch] 写出 {len(records)} 条 -> {path.name}")
|