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(
|
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:
|
||||||
|
return None
|
||||||
try:
|
try:
|
||||||
data = json.loads(m.group(1))
|
data = json.loads(m.group(1))
|
||||||
except Exception:
|
except Exception:
|
||||||
data = None
|
return None
|
||||||
if isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
|
return None
|
||||||
scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data
|
scope = data.get("__DEFAULT_SCOPE__") if isinstance(data.get("__DEFAULT_SCOPE__"), dict) else data
|
||||||
|
|
||||||
|
# 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():
|
for _key, val in (scope or {}).items():
|
||||||
if not isinstance(val, dict):
|
if not isinstance(val, dict):
|
||||||
continue
|
continue
|
||||||
user_info = val.get("userInfo") if isinstance(val.get("userInfo"), dict) else None
|
user_info = val.get("userInfo") if isinstance(val.get("userInfo"), dict) else None
|
||||||
if user_info and isinstance(user_info.get("user"), dict):
|
if user_info and isinstance(user_info.get("user"), dict):
|
||||||
stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
|
stats = user_info.get("stats") if isinstance(user_info.get("stats"), dict) else {}
|
||||||
return _parse_user_blob(user_info["user"], stats)
|
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
|
webapp = scope.get("webapp.app-context") if isinstance(scope, dict) else None
|
||||||
if isinstance(webapp, dict):
|
if isinstance(webapp, dict):
|
||||||
u = webapp.get("user") if isinstance(webapp.get("user"), dict) else None
|
u = webapp.get("user") if isinstance(webapp.get("user"), dict) else None
|
||||||
if u:
|
if u:
|
||||||
return _parse_user_blob(u, {})
|
parsed = _parse_user_blob(u, {})
|
||||||
|
# merge onto best if we only have thin context user
|
||||||
m2 = re.search(r'<script[^>]+id="SIGI_STATE"[^>]*>(\{.*?\})</script>', html, re.DOTALL)
|
if best:
|
||||||
if m2:
|
for k, v in parsed.items():
|
||||||
try:
|
if v and not best.get(k):
|
||||||
data = json.loads(m2.group(1))
|
best[k] = v
|
||||||
except Exception:
|
return best
|
||||||
data = None
|
return parsed
|
||||||
if isinstance(data, dict):
|
return best
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
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.
|
||||||
|
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:
|
try:
|
||||||
html = sess.get("https://www.tiktok.com/", timeout=25).text or ""
|
html = sess.get(page, timeout=30).text or ""
|
||||||
profile = _extract_from_rehydration(html)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
profile = None
|
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 可能失效或机房不匹配)")
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user