From 9fbf5ec04a1a00b645ba09336c156669e5c83bac Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 03:19:18 -0500 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BB=8E=20TikTok=20@=E4=B8=BB=E9=A1=B5?= =?UTF-8?q?=E6=8A=93=E5=8F=96=E5=AE=8C=E6=95=B4=E5=A4=B4=E5=83=8F=E4=B8=8E?= =?UTF-8?q?=E7=B2=89=E4=B8=9D/=E8=A7=86=E9=A2=91=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- backend/app/tiktok_profile.py | 120 ++++++++++++++++++++++------------ 1 file changed, 80 insertions(+), 40 deletions(-) diff --git a/backend/app/tiktok_profile.py b/backend/app/tiktok_profile.py index 1c8693b..1f163d4 100644 --- a/backend/app/tiktok_profile.py +++ b/backend/app/tiktok_profile.py @@ -47,6 +47,12 @@ def _parse_user_blob(user: dict[str, Any], stats: dict[str, Any] | None = None) avatar = str( user.get("avatarLarger") or user.get("avatarMedium") or user.get("avatarThumb") or "" ).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 { "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("@"), @@ -68,41 +74,49 @@ def _extract_from_rehydration(html: str) -> dict[str, Any] | None: html, re.DOTALL, ) - if m: - try: - data = json.loads(m.group(1)) - except Exception: - data = None - if isinstance(data, dict): - scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data - for _key, val in (scope or {}).items(): - if not isinstance(val, dict): - 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, {}) + if not m: + return None + try: + data = json.loads(m.group(1)) + except Exception: + return None + if not isinstance(data, dict): + return None + scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data - m2 = re.search(r']+id="SIGI_STATE"[^>]*>(\{.*?\})', html, re.DOTALL) - if m2: - try: - data = json.loads(m2.group(1)) - except Exception: - data = None - if isinstance(data, dict): - 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 {} - stats_mod = user_mod.get("stats") if isinstance(user_mod.get("stats"), dict) else {} - for uid, user in users.items(): - if isinstance(user, dict): - st = stats_mod.get(uid) if isinstance(stats_mod.get(uid), dict) else {} - return _parse_user_blob(user, st) - return None + # Prefer full profile module (has avatar + stats) + detail = scope.get("webapp.user-detail") if isinstance(scope, dict) else None + if isinstance(detail, dict): + user_info = detail.get("userInfo") if isinstance(detail.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) + + best: dict[str, Any] | None = None + for _key, val in (scope or {}).items(): + if not isinstance(val, dict): + 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 {} + 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: @@ -201,12 +215,38 @@ def fetch_profile_for_channel(channel_pk: str, *, username_hint: str = "") -> di unique = _resolve_unique_id(sess, hint) profile = _fetch_user_detail(sess, unique) if unique else None - if not profile: - try: - html = sess.get("https://www.tiktok.com/", timeout=25).text or "" - profile = _extract_from_rehydration(html) - except Exception: - profile = None + # Official web JSON often empty from datacenter IPs; scrape @page / home rehydration instead. + if not profile or not profile.get("avatar_cdn") or not ( + profile.get("follower_count") or profile.get("video_count") + ): + pages = [] + 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")): raise ValueError("未能从 TikTok 拉取账号资料(Cookie 可能失效或机房不匹配)")