149 lines
5.5 KiB
Python
149 lines
5.5 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
实测探测消息页(/web/geek/chat)左侧联系人列表真实 DOM:
|
||
1. 原生开标签页到消息页,等 SPA 渲染;
|
||
2. 统计各候选选择器命中数;
|
||
3. 导出前若干条列表项的 class / innerText / 外层 HTML;
|
||
4. 顺带探测输入框与发送按钮候选。
|
||
用法:python -m client.debug_chat_probe
|
||
产物:client/data/debug/chat_list_probe.txt
|
||
"""
|
||
import json
|
||
import time
|
||
from pathlib import Path
|
||
|
||
import requests
|
||
import websocket
|
||
|
||
CDP = "http://127.0.0.1:9222"
|
||
CHAT_URL = "https://www.zhipin.com/web/geek/chat"
|
||
OUT = Path(__file__).resolve().parent / "data" / "debug" / "chat_list_probe5.txt"
|
||
|
||
_msg_id = 0
|
||
|
||
|
||
def send(ws, method, params=None):
|
||
global _msg_id
|
||
_msg_id += 1
|
||
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||
while True:
|
||
msg = json.loads(ws.recv())
|
||
if msg.get("id") == _msg_id:
|
||
return msg.get("result") or {}
|
||
|
||
|
||
def evaluate(ws, expression):
|
||
return send(ws, "Runtime.evaluate",
|
||
{"expression": expression, "returnByValue": True}) \
|
||
.get("result", {}).get("value")
|
||
|
||
|
||
PROBE_JS = """(() => {
|
||
const fs = [];
|
||
// 1. message-status 全部 class 取值
|
||
const statusSet = {};
|
||
for (const el of document.querySelectorAll('.message-status')) {
|
||
const k = String(el.className).trim();
|
||
statusSet[k] = (statusSet[k] || 0) + 1;
|
||
}
|
||
fs.push('== message-status 取值 ==');
|
||
Object.entries(statusSet).forEach(([k, n]) => fs.push(' ' + k + ' -> ' + n));
|
||
|
||
// 2. 点击第 1 条列表项(只读验证,不发消息)
|
||
const wraps = [...document.querySelectorAll('.friend-content-warp')];
|
||
const lis = [...new Set(wraps.map(w => w.closest('li')).filter(Boolean))];
|
||
fs.push('== li 总数:' + lis.length + ' ==');
|
||
if (!lis.length) return fs.join('\\n');
|
||
const target = lis[0];
|
||
const nameEl = target.querySelector('.name-text');
|
||
fs.push('点击目标:' + (nameEl ? nameEl.innerText.trim() : '未知'));
|
||
target.click();
|
||
return fs.join('\\n');
|
||
})()"""
|
||
|
||
# 点击后轮询右侧会话区结构(消息气泡/输入框/发送按钮)
|
||
CONV_JS = """(() => {
|
||
const fs = [];
|
||
const conv = document.querySelector('.chat-conversation');
|
||
if (!conv) { fs.push('无 .chat-conversation'); return fs.join('\\n'); }
|
||
fs.push('== conversation children ==');
|
||
[...conv.children].forEach(c => fs.push(' <' + c.tagName + ' class=' + String(c.className).slice(0, 80) + '>'));
|
||
// 消息气泡候选 class 统计
|
||
const clsCount = {};
|
||
for (const el of conv.querySelectorAll('[class]')) {
|
||
for (const c of String(el.className).split(/\\s+/)) {
|
||
if (/msg|item|message|bubble|text|self|other/i.test(c)) clsCount[c] = (clsCount[c] || 0) + 1;
|
||
}
|
||
}
|
||
fs.push('== 会话区高频 class ==');
|
||
Object.entries(clsCount).sort((a, b) => b[1] - a[1]).slice(0, 25)
|
||
.forEach(([k, n]) => fs.push(' .' + k + ' -> ' + n));
|
||
// 最后一条消息候选样本(取出现次数多的容器类下的最后 2 个)
|
||
const items = [...conv.querySelectorAll('.chat-message .item, [class*="msg-item"], [class*="message-item"], .item-myself, .item-other')];
|
||
fs.push('== 消息条目候选数:' + items.length + ' ==');
|
||
items.slice(-2).forEach((el, i) => {
|
||
fs.push('--- msg ' + i + ' class=' + String(el.className).slice(0, 100));
|
||
fs.push(' text: ' + (el.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 120));
|
||
fs.push(' html: ' + el.outerHTML.replace(/\\s+/g, ' ').slice(0, 1200));
|
||
});
|
||
// 输入框与发送按钮(会话打开后才渲染)
|
||
const ta = conv.querySelector('textarea') || document.querySelector('.chat-conversation textarea');
|
||
fs.push('== 输入框:' + (ta ? 'textarea.input=' + ta.className : '无') + ' ==');
|
||
const sends = [...document.querySelectorAll('a,button,div,span')]
|
||
.filter(e => (e.innerText || '').trim() === '发送' && e.offsetHeight > 0);
|
||
fs.push('== 发送按钮候选:' + sends.length + ' ==');
|
||
sends.slice(0, 3).forEach(e => fs.push(' <' + e.tagName + ' class=' + String(e.className).slice(0, 80) + '>'));
|
||
return fs.join('\\n');
|
||
})()"""
|
||
|
||
|
||
def main():
|
||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||
lines = []
|
||
|
||
def log(*a):
|
||
s = " ".join(str(x) for x in a)
|
||
lines.append(s)
|
||
OUT.write_text("\n".join(lines), encoding="utf-8")
|
||
try:
|
||
print(f"[probe] line {len(lines)} written", flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 已有聊天页标签则复用,否则新开
|
||
tab = None
|
||
for t in requests.get(f"{CDP}/json", timeout=5).json():
|
||
if "/web/geek/chat" in (t.get("url") or "") and t.get("webSocketDebuggerUrl"):
|
||
tab = t
|
||
break
|
||
if not tab:
|
||
r = requests.put(f"{CDP}/json/new?{CHAT_URL}", timeout=10)
|
||
if r.status_code == 405:
|
||
r = requests.get(f"{CDP}/json/new?{CHAT_URL}", timeout=10)
|
||
tab = r.json()
|
||
time.sleep(10) # 等 SPA 挂载
|
||
|
||
log("== URL ==", tab.get("url"))
|
||
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||
try:
|
||
for attempt in range(3):
|
||
val = evaluate(ws, PROBE_JS)
|
||
if val:
|
||
log(val)
|
||
break
|
||
time.sleep(3)
|
||
# 点击后等会话区渲染,再读结构(最多等 10s)
|
||
for i in range(5):
|
||
time.sleep(2)
|
||
conv_val = evaluate(ws, CONV_JS)
|
||
if conv_val and '消息条目候选数:0' not in conv_val:
|
||
break
|
||
log(conv_val or '会话区探测为空')
|
||
finally:
|
||
ws.close()
|
||
log("== DONE ==")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|