|
@@ -0,0 +1,192 @@
|
|
|
|
|
+# -*- coding: utf-8 -*-
|
|
|
|
|
+"""浏览器内采集引擎(联调清单 C4):Edge+CDP 打开对标主页 → 自动滚动翻页 →
|
|
|
|
|
+监听 Network 响应收数据。a_bogus 等反爬签名由页面真实前端 JS 完成,白盒零逆向。
|
|
|
|
|
+
|
|
|
|
|
+对齐原工具架构(C线§2.7「签名/复杂计算经 WebView2 执行 JS」;E线 M1/M5 网页
|
|
|
|
|
+通道)。复用 login 的持久登录 profile(.login-profile-web),已登录即免扫码。
|
|
|
|
|
+
|
|
|
|
|
+注意:与 login 抓CK共用同一 profile——Edge 同 profile 单实例,两者不要同时开
|
|
|
|
|
+(后启动的进程会把页面让给先前实例,新调试端口不生效)。
|
|
|
|
|
+"""
|
|
|
|
|
+import json
|
|
|
|
|
+import random
|
|
|
|
|
+import subprocess
|
|
|
|
|
+import time
|
|
|
|
|
+import urllib.request
|
|
|
|
|
+
|
|
|
|
|
+from . import config
|
|
|
|
|
+from .login import find_edge
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class BrowserError(Exception):
|
|
|
|
|
+ """浏览器采集失败(Edge 缺失/CDP 异常/响应解析失败)。"""
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def merge_feeds(pages):
|
|
|
|
|
+ """多页 feeds 合并去重(按 photo 主键),保序。
|
|
|
|
|
+
|
|
|
|
|
+ 兼容 iOS 形态(photo_id)与网页 graphql 形态(photo.id);photo 包一层的
|
|
|
|
|
+ 网页源以内层 id 为键。
|
|
|
|
|
+ """
|
|
|
|
|
+ seen, out = set(), []
|
|
|
|
|
+ for feeds in pages:
|
|
|
|
|
+ for f in feeds:
|
|
|
|
|
+ if not isinstance(f, dict):
|
|
|
|
|
+ continue
|
|
|
|
|
+ p = f.get('photo') if isinstance(f.get('photo'), dict) else f
|
|
|
|
|
+ key = p.get('id') or p.get('photo_id') or p.get('photoId')
|
|
|
|
|
+ if not key or key in seen:
|
|
|
|
|
+ continue
|
|
|
|
|
+ seen.add(key)
|
|
|
|
|
+ out.append(f)
|
|
|
|
|
+ return out
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class EdgeSession:
|
|
|
|
|
+ """单次采集会话:启动 Edge(app 模式,持久 profile)→ CDP 控制 → 关闭。"""
|
|
|
|
|
+
|
|
|
|
|
+ def __init__(self, url, profile='web', port=None):
|
|
|
|
|
+ edge = find_edge()
|
|
|
|
|
+ if not edge:
|
|
|
|
|
+ raise BrowserError('未找到系统 Edge(Program Files\\Microsoft\\Edge)')
|
|
|
|
|
+ self.port = port or random.randint(9400, 9499)
|
|
|
|
|
+ self.user_data = str(config.ROOT / f'.login-profile-{profile}')
|
|
|
|
|
+ self.proc = subprocess.Popen(
|
|
|
|
|
+ [edge, f'--remote-debugging-port={self.port}',
|
|
|
|
|
+ f'--user-data-dir={self.user_data}', '--no-first-run',
|
|
|
|
|
+ '--no-default-browser-check', '--window-size=1100,900',
|
|
|
|
|
+ f'--app={url}'])
|
|
|
|
|
+ self.ws = None
|
|
|
|
|
+ self._id = 0
|
|
|
|
|
+ self.responses = [] # [(requestId, url)] 响应头事件缓存
|
|
|
|
|
+ self._wait_port(15)
|
|
|
|
|
+ self._connect()
|
|
|
|
|
+
|
|
|
|
|
+ # ---------------- CDP 基建 ----------------
|
|
|
|
|
+
|
|
|
|
|
+ def _wait_port(self, timeout):
|
|
|
|
|
+ end = time.time() + timeout
|
|
|
|
|
+ while time.time() < end:
|
|
|
|
|
+ try:
|
|
|
|
|
+ urllib.request.urlopen(
|
|
|
|
|
+ f'http://localhost:{self.port}/json/version', timeout=1).read()
|
|
|
|
|
+ return
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ time.sleep(0.5)
|
|
|
|
|
+ raise BrowserError(f'Edge 调试端口 {self.port} 未就绪')
|
|
|
|
|
+
|
|
|
|
|
+ def _connect(self):
|
|
|
|
|
+ import websocket
|
|
|
|
|
+ tabs = json.loads(urllib.request.urlopen(
|
|
|
|
|
+ f'http://localhost:{self.port}/json/list', timeout=3).read())
|
|
|
|
|
+ ws_url = next((t['webSocketDebuggerUrl'] for t in tabs
|
|
|
|
|
+ if t.get('type') == 'page' and t.get('webSocketDebuggerUrl')),
|
|
|
|
|
+ None)
|
|
|
|
|
+ if not ws_url:
|
|
|
|
|
+ raise BrowserError('CDP 无 page 目标')
|
|
|
|
|
+ # Edge/Chrome 111+ 拒带 Origin 头的 CDP 握手,须抑制(login 同坑)
|
|
|
|
|
+ self.ws = websocket.create_connection(ws_url, timeout=10, suppress_origin=True)
|
|
|
|
|
+ self._call('Network.enable')
|
|
|
|
|
+
|
|
|
|
|
+ def _keep(self, msg):
|
|
|
|
|
+ """缓存 Network.responseReceived 事件(响应头,含 URL)。"""
|
|
|
|
|
+ if msg.get('method') == 'Network.responseReceived':
|
|
|
|
|
+ p = msg.get('params', {})
|
|
|
|
|
+ self.responses.append((p.get('requestId'),
|
|
|
|
|
+ (p.get('response') or {}).get('url', '')))
|
|
|
|
|
+
|
|
|
|
|
+ def _call(self, method, params=None):
|
|
|
|
|
+ """同步调用:发命令收应答(途中事件顺手缓存)。"""
|
|
|
|
|
+ self._id += 1
|
|
|
|
|
+ rid = self._id
|
|
|
|
|
+ self.ws.send(json.dumps({'id': rid, 'method': method, 'params': params or {}}))
|
|
|
|
|
+ self.ws.settimeout(15)
|
|
|
|
|
+ while True:
|
|
|
|
|
+ msg = json.loads(self.ws.recv())
|
|
|
|
|
+ if msg.get('id') == rid:
|
|
|
|
|
+ if 'error' in msg:
|
|
|
|
|
+ raise BrowserError(f'{method}: '
|
|
|
|
|
+ + str(msg['error'].get('message'))[:120])
|
|
|
|
|
+ return msg.get('result', {})
|
|
|
|
|
+ self._keep(msg)
|
|
|
|
|
+
|
|
|
|
|
+ # ---------------- 行为 ----------------
|
|
|
|
|
+
|
|
|
|
|
+ def reload(self):
|
|
|
|
|
+ """重载页面:让首屏请求发生在 Network.enable 之后(否则错过首份数据)。"""
|
|
|
|
|
+ self._call('Page.enable')
|
|
|
|
|
+ self._call('Page.reload')
|
|
|
|
|
+
|
|
|
|
|
+ def eval_js(self, expr):
|
|
|
|
|
+ r = self._call('Runtime.evaluate', {'expression': expr,
|
|
|
|
|
+ 'returnByValue': True})
|
|
|
|
|
+ return (r.get('result') or {}).get('value')
|
|
|
|
|
+
|
|
|
|
|
+ def drain(self, idle_sec=2.0):
|
|
|
|
|
+ """收事件直到 idle_sec 无新事件(响应头缓存进 self.responses)。"""
|
|
|
|
|
+ self.ws.settimeout(idle_sec)
|
|
|
|
|
+ while True:
|
|
|
|
|
+ try:
|
|
|
|
|
+ msg = json.loads(self.ws.recv())
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return
|
|
|
|
|
+ self._keep(msg)
|
|
|
|
|
+
|
|
|
|
|
+ def scroll(self, times=5, gap=1.6, early_stop=None):
|
|
|
|
|
+ """滚到底部触发翻页加载;early_stop() 为真提前停。"""
|
|
|
|
|
+ for _ in range(times):
|
|
|
|
|
+ self.eval_js('window.scrollTo(0, document.body.scrollHeight)')
|
|
|
|
|
+ time.sleep(gap)
|
|
|
|
|
+ self.drain(1.2)
|
|
|
|
|
+ if early_stop and early_stop():
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
|
|
+ def bodies(self, url_frag):
|
|
|
|
|
+ """取已缓存响应中 URL 含 url_frag 的 JSON body(非 JSON 自动跳过)。"""
|
|
|
|
|
+ out = []
|
|
|
|
|
+ for req_id, url in self.responses:
|
|
|
|
|
+ if url_frag not in url:
|
|
|
|
|
+ continue
|
|
|
|
|
+ try:
|
|
|
|
|
+ r = self._call('Network.getResponseBody', {'requestId': req_id})
|
|
|
|
|
+ out.append(json.loads(r.get('body') or ''))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ continue
|
|
|
|
|
+ return out
|
|
|
|
|
+
|
|
|
|
|
+ def close(self):
|
|
|
|
|
+ try:
|
|
|
|
|
+ if self.ws:
|
|
|
|
|
+ self.ws.close()
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+ try:
|
|
|
|
|
+ self.proc.terminate()
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def collect_profile_feeds(uid, max_scrolls=2, first_wait=4.0):
|
|
|
|
|
+ """打开对标主页 → 重载页面 → (可选)滚动 → 收取作品列表响应的 feeds。
|
|
|
|
|
+
|
|
|
|
|
+ 现行快手前端走 rest/v/profile/feed(顶层 feeds/pcursor,C4 实测),
|
|
|
|
|
+ 兼容老 graphql 形态;监控场景只需最新一页(新作品在头部),滚动仅作补充。
|
|
|
|
|
+ 返回合并去重后的原始 feeds 列表,解析统一走 collect._extract_page。
|
|
|
|
|
+ """
|
|
|
|
|
+ from . import collect as _c
|
|
|
|
|
+ s = EdgeSession(f'https://www.kuaishou.com/profile/{uid}')
|
|
|
|
|
+ try:
|
|
|
|
|
+ s.reload() # 首屏请求重发于 Network.enable 之后
|
|
|
|
|
+ time.sleep(first_wait)
|
|
|
|
|
+ s.drain(2.0)
|
|
|
|
|
+ s.scroll(max_scrolls)
|
|
|
|
|
+ s.drain(2.0)
|
|
|
|
|
+ pages = []
|
|
|
|
|
+ for frag in ('/rest/v/profile/feed', '/graphql'):
|
|
|
|
|
+ for j in s.bodies(frag):
|
|
|
|
|
+ feeds, _pc = _c._extract_page(j)
|
|
|
|
|
+ if feeds:
|
|
|
|
|
+ pages.append(feeds)
|
|
|
|
|
+ return merge_feeds(pages)
|
|
|
|
|
+ finally:
|
|
|
|
|
+ s.close()
|