fix: 从 TikTok @主页抓取完整头像与粉丝/视频数

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 03:19:18 -05:00
parent 60054cd188
commit 9fbf5ec04a

View File

@ -47,6 +47,12 @@ def _parse_user_blob(user: dict[str, Any], stats: dict[str, Any] | None = None)
avatar = str( avatar = str(
user.get("avatarLarger") or user.get("avatarMedium") or user.get("avatarThumb") or "" user.get("avatarLarger") or user.get("avatarMedium") or user.get("avatarThumb") or ""
).strip() ).strip()
if not avatar:
uris = user.get("avatarUri")
if isinstance(uris, list) and uris:
avatar = str(uris[0] or "").strip()
elif isinstance(uris, str):
avatar = uris.strip()
return { return {
"tiktok_uid": str(user.get("id") or user.get("uid") or "").strip(), "tiktok_uid": str(user.get("id") or user.get("uid") or "").strip(),
"tiktok_username": str(user.get("uniqueId") or user.get("unique_id") or "").strip().lstrip("@"), "tiktok_username": str(user.get("uniqueId") or user.get("unique_id") or "").strip().lstrip("@"),
@ -68,41 +74,49 @@ def _extract_from_rehydration(html: str) -> dict[str, Any] | None:
html, html,
re.DOTALL, re.DOTALL,
) )
if m: if not m:
try: return None
data = json.loads(m.group(1)) try:
except Exception: data = json.loads(m.group(1))
data = None except Exception:
if isinstance(data, dict): return None
scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data if not isinstance(data, dict):
for _key, val in (scope or {}).items(): return None
if not isinstance(val, dict): scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data
continue
user_info = val.get("userInfo") if isinstance(val.get("userInfo"), dict) else None
if user_info and isinstance(user_info.get("user"), dict):
stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
return _parse_user_blob(user_info["user"], stats)
webapp = scope.get("webapp.app-context") if isinstance(scope, dict) else None
if isinstance(webapp, dict):
u = webapp.get("user") if isinstance(webapp.get("user"), dict) else None
if u:
return _parse_user_blob(u, {})
m2 = re.search(r'<script[^>]+id="SIGI_STATE"[^>]*>(\{.*?\})</script>', html, re.DOTALL) # Prefer full profile module (has avatar + stats)
if m2: detail = scope.get("webapp.user-detail") if isinstance(scope, dict) else None
try: if isinstance(detail, dict):
data = json.loads(m2.group(1)) user_info = detail.get("userInfo") if isinstance(detail.get("userInfo"), dict) else None
except Exception: if user_info and isinstance(user_info.get("user"), dict):
data = None stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
if isinstance(data, dict): return _parse_user_blob(user_info["user"], stats)
user_mod = data.get("UserModule") if isinstance(data.get("UserModule"), dict) else {}
users = user_mod.get("users") if isinstance(user_mod.get("users"), dict) else {} best: dict[str, Any] | None = None
stats_mod = user_mod.get("stats") if isinstance(user_mod.get("stats"), dict) else {} for _key, val in (scope or {}).items():
for uid, user in users.items(): if not isinstance(val, dict):
if isinstance(user, dict): continue
st = stats_mod.get(uid) if isinstance(stats_mod.get(uid), dict) else {} user_info = val.get("userInfo") if isinstance(val.get("userInfo"), dict) else None
return _parse_user_blob(user, st) if user_info and isinstance(user_info.get("user"), dict):
return None stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
parsed = _parse_user_blob(user_info["user"], stats)
if parsed.get("avatar_cdn") or parsed.get("follower_count") or parsed.get("video_count"):
return parsed
best = best or parsed
webapp = scope.get("webapp.app-context") if isinstance(scope, dict) else None
if isinstance(webapp, dict):
u = webapp.get("user") if isinstance(webapp.get("user"), dict) else None
if u:
parsed = _parse_user_blob(u, {})
# merge onto best if we only have thin context user
if best:
for k, v in parsed.items():
if v and not best.get(k):
best[k] = v
return best
return parsed
return best
def _fetch_user_detail(sess: requests.Session, unique_id: str) -> dict[str, Any] | None: def _fetch_user_detail(sess: requests.Session, unique_id: str) -> dict[str, Any] | None:
@ -201,12 +215,38 @@ def fetch_profile_for_channel(channel_pk: str, *, username_hint: str = "") -> di
unique = _resolve_unique_id(sess, hint) unique = _resolve_unique_id(sess, hint)
profile = _fetch_user_detail(sess, unique) if unique else None profile = _fetch_user_detail(sess, unique) if unique else None
if not profile: # Official web JSON often empty from datacenter IPs; scrape @page / home rehydration instead.
try: if not profile or not profile.get("avatar_cdn") or not (
html = sess.get("https://www.tiktok.com/", timeout=25).text or "" profile.get("follower_count") or profile.get("video_count")
profile = _extract_from_rehydration(html) ):
except Exception: pages = []
profile = None if unique:
pages.append(f"https://www.tiktok.com/@{unique}")
pages.append("https://www.tiktok.com/")
for page in pages:
try:
html = sess.get(page, timeout=30).text or ""
except Exception:
continue
scraped = _extract_from_rehydration(html)
if not scraped:
continue
if not profile:
profile = scraped
else:
for k, v in scraped.items():
if v and not profile.get(k):
profile[k] = v
elif k in {"follower_count", "following_count", "video_count", "heart_count"} and int(
v or 0
) > int(profile.get(k) or 0):
profile[k] = v
elif k == "avatar_cdn" and v and not profile.get("avatar_cdn"):
profile[k] = v
if profile.get("avatar_cdn") and (
profile.get("follower_count") or profile.get("video_count") or profile.get("nickname")
):
break
if not profile or not (profile.get("tiktok_uid") or profile.get("tiktok_username") or profile.get("nickname")): if not profile or not (profile.get("tiktok_uid") or profile.get("tiktok_username") or profile.get("nickname")):
raise ValueError("未能从 TikTok 拉取账号资料(Cookie 可能失效或机房不匹配)") raise ValueError("未能从 TikTok 拉取账号资料(Cookie 可能失效或机房不匹配)")