瀏覽代碼

feat: 监控资料刷新改走网页SSR抓取(M8 web版)

- refresh_monitor_stats_web:profile页SSR HTML抠user_name+ownerCount落库
  (az3-api版需APP型did,result=40不可用,联调清单C3)
- _parse_profile_html纯函数+用例;UI「刷新资料」/cli monitor refresh 切换
- 实测:字母串ID解析正常;数字userDefineId页面为空壳(SSR不解析),
  监控池须用主页网址原样ID
wubinggen 3 月之前
父節點
當前提交
b4a83d1aba

+ 1 - 1
白盒重建/kuaishou_tool/cli.py

@@ -85,7 +85,7 @@ def main(argv=None):
         elif sub == 'del' and len(argv) >= 3:
             print('已删除' if collect.delete_monitor(argv[2]) else '记录不存在')
         elif sub == 'refresh':
-            n = collect.refresh_monitor_stats(cfg, uid=argv[2] if len(argv) > 2 else None)
+            n = collect.refresh_monitor_stats_web(cfg, uid=argv[2] if len(argv) > 2 else None)
             print(f'资料刷新成功 {n} 个账号')
             _monitor_list()
         else:

+ 50 - 0
白盒重建/kuaishou_tool/collect.py

@@ -105,6 +105,56 @@ def delete_monitor(uid: str) -> bool:
     return True
 
 
+def _parse_profile_html(body: str) -> dict:
+    """从 profile 页 SSR HTML 抠资料(M8 web 版):user_name + ownerCount。
+
+    页面无作品列表(C4 已证),但用户资料是服务端渲染内嵌的——
+    `"user_name":"泽小泽_"`、`"ownerCount":{"fan":…,"follow":…,"photo_public":…}`。
+    """
+    d = {}
+    m = re.search(r'"user_name":"([^"]*)"', body or '')
+    if m:
+        d['name'] = m.group(1)
+    i = (body or '').find('ownerCount')
+    if i >= 0:
+        seg = body[i:i + 300]
+        for key, out in (('fan', 'fensishu'), ('follow', 'guanzhushu'),
+                         ('photo_public', 'zuopinshu')):
+            mm = re.search(rf'"{key}":(\d+)', seg)
+            if mm:
+                d[out] = int(mm.group(1))
+    return d
+
+
+def refresh_monitor_stats_web(cfg, uid: str = None) -> int:
+    """资料刷新(web 版):抓 profile 页 SSR HTML 抠 ownerCount 落库。
+
+    az3-api 版 refresh_monitor_stats 需 APP 型 did(result=40,联调清单C3),
+    此为白盒可行路径;用 anchor 首行的网页CK请求。返回成功刷新数。
+    """
+    import requests as _rq
+    from .httpclient import WEB_UA
+    rows = (db.query('SELECT uid FROM monitoring WHERE uid=?', (uid,)) if uid
+            else db.query('SELECT uid FROM monitoring ORDER BY id'))
+    ck_rows = db.query('SELECT cookie1 FROM anchor ORDER BY id LIMIT 1')
+    cookie = ck_rows[0]['cookie1'] if ck_rows else ''
+    n = 0
+    for r in rows:
+        try:
+            resp = _rq.get(f'https://www.kuaishou.com/profile/{r["uid"]}',
+                           headers={'Cookie': cookie, 'User-Agent': WEB_UA},
+                           timeout=20)
+            d = _parse_profile_html(resp.text)
+            if not (d.get('name') or d.get('fensishu') is not None):
+                continue                   # 页面无资料(UID错/风控页)
+            d['uid'] = r['uid']
+            update_monitor_stats(d)
+            n += 1
+        except Exception:
+            continue                       # 单账号失败不中断批次
+    return n
+
+
 def refresh_monitor_stats(cfg, uid: str = None) -> int:
     """资料查询刷新监控账号统计(E线 M8:az3-api profile,iOS伪装)。
 

+ 1 - 1
白盒重建/kuaishou_tool/ui.py

@@ -536,7 +536,7 @@ class App(tk.Tk):
             self._set_status(f'资料刷新 {n} 个账号' if err is None else f'资料刷新失败:{err}')
             self.refresh_monitor()
 
-        self._bg(lambda: collect.refresh_monitor_stats(self.cfg), done)
+        self._bg(lambda: collect.refresh_monitor_stats_web(self.cfg), done)
 
     def _poll_once(self):
         """采集一轮(浏览器通道,C4:Edge 内滚动收数据,过 a_bogus 签名)。"""

+ 1 - 1
白盒重建/tests/test_cli.py

@@ -53,7 +53,7 @@ def test_monitor_del_and_refresh(_env, monkeypatch, capsys):
     monkeypatch.setattr(collect, 'delete_monitor', lambda uid: True)
     assert cli.main(['monitor', 'del', 'u1']) == 0
     assert '已删除' in capsys.readouterr().out
-    monkeypatch.setattr(collect, 'refresh_monitor_stats', lambda cfg, uid=None: 2)
+    monkeypatch.setattr(collect, 'refresh_monitor_stats_web', lambda cfg, uid=None: 2)
     assert cli.main(['monitor', 'refresh', 'u9']) == 0
     out = capsys.readouterr().out
     assert '资料刷新成功 2 个账号' in out

+ 12 - 0
白盒重建/tests/test_collect.py

@@ -344,6 +344,18 @@ def test_refresh_monitor_stats():
     assert 'Pro' in db.query("SELECT name FROM monitoring WHERE uid='u1'")[0]['name']
 
 
+def test_parse_profile_html():
+    """M8 web 版:SSR 主页 HTML 抠 user_name + ownerCount。"""
+    html = ('...{"user_id":"3xsn","user_name":"泽小泽_","headurl":"http://x/uhead",'
+            '"userId":"494608718","ownerCount":{"fan":579174,"like":17688318,'
+            '"follow":177,"photo_public":333},"isUserIso...}')
+    d = collect._parse_profile_html(html)
+    assert d['name'] == '泽小泽_'
+    assert d['fensishu'] == 579174 and d['guanzhushu'] == 177
+    assert d['zuopinshu'] == 333
+    assert collect._parse_profile_html('风控页无资料') == {}
+
+
 def test_resolve_photo():
     """R1 单作品解析:分享文本提链接/短链跟随/result 失效判定/item 字段统一。"""
     _fresh()