fix: 从 TikTok @主页抓取完整头像与粉丝/视频数
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
60054cd188
commit
9fbf5ec04a
@ -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'<script[^>]+id="SIGI_STATE"[^>]*>(\{.*?\})</script>', 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 可能失效或机房不匹配)")
|
||||
|
||||
Loading…
Reference in New Issue
Block a user