"""八次探测:detail.json 明文字段 / 可信点击立即沟通 / 聊天页结构 / 右侧面板 JD 容器""" import json import time from pathlib import Path import websocket from client.browser.cdp_lite import LiteCDP from client.browser.manager import BrowserManager OUT = Path(__file__).resolve().parent / "data" / "debug" / "job_page_probe8.txt" _lines: list[str] = [] def log(*a): s = " ".join(str(x) for x in a) _lines.append(s) OUT.write_text("\n".join(_lines), encoding="utf-8") class Session: def __init__(self, ws_url): self.ws = websocket.create_connection(ws_url, timeout=30) self._id = 0 def call(self, method, params=None, timeout=10): self._id += 1 mid = self._id self.ws.send(json.dumps({"id": mid, "method": method, "params": params or {}})) self.ws.settimeout(timeout) while True: msg = json.loads(self.ws.recv()) if msg.get("id") == mid: return msg.get("result") or {} def eval_js(self, expr, timeout=10): return (self.call("Runtime.evaluate", {"expression": expr, "returnByValue": True}, timeout) .get("result", {}).get("value")) def pump(self, duration): self.ws.settimeout(0.5) end = time.time() + duration while time.time() < end: try: yield json.loads(self.ws.recv()) except Exception: continue def click_at(self, x, y): self.call("Input.dispatchMouseEvent", { "type": "mousePressed", "x": x, "y": y, "button": "left", "clickCount": 1}) time.sleep(0.08) self.call("Input.dispatchMouseEvent", { "type": "mouseReleased", "x": x, "y": y, "button": "left", "clickCount": 1}) def close(self): try: self.ws.close() except Exception: pass def main(): BrowserManager().ensure_browser_started() lite = LiteCDP() tab = lite.open_tab("https://www.zhipin.com/web/geek/jobs") s = Session(tab["webSocketDebuggerUrl"]) s.call("Network.enable") s.eval_js("""(() => { const inp = document.querySelector('input[placeholder*="搜索"]'); const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set; setter.call(inp, 'java'); inp.dispatchEvent(new Event('input', {bubbles: true})); document.querySelector('.search-btn').click(); return true; })()""") time.sleep(5) # 点第二张卡片(避免首张已选中不触发请求) s.eval_js("""(() => { const c = document.querySelectorAll('.job-card-wrap')[1]; if (c) c.click(); return !!c; })()""") req_urls: dict[str, str] = {} bodies: list[str] = [] for msg in s.pump(5): m = msg.get("method") if m == "Network.responseReceived": u = msg["params"]["response"]["url"] if "detail.json" in u: req_urls[msg["params"]["requestId"]] = u elif m == "Network.loadingFinished": rid = msg["params"]["requestId"] if rid in req_urls: bodies.append(s.call("Network.getResponseBody", {"requestId": rid}).get("body", "")) for body in bodies[:1]: try: zp = json.loads(body).get("zpData", {}) ji = zp.get("jobInfo") or zp log("== 1) detail.json ==", json.dumps({ "zpKeys": list(zp.keys())[:20], "jiKeys": list(ji.keys())[:40], "salary": ji.get("salaryDesc") or ji.get("salary"), "jdHead": (ji.get("jobDesc") or "")[:80], }, ensure_ascii=False)[:2000]) except Exception as e: log("== 1) 解析失败 ==", e, body[:300]) # 右侧面板 JD 容器 r2 = s.eval_js("""(() => { const hits = [...document.querySelectorAll('div,section')] .filter(d => (d.innerText || '').trim().startsWith('职位描述') && d.innerText.length < 5000) .map(d => ({cls: d.className, len: d.innerText.length})) .sort((a, b) => a.len - b.len); return JSON.stringify(hits.slice(0, 4)); })()""") log("== 2) 右侧JD容器 ==", r2) # 可信点击 .op-btn-chat box = s.eval_js("""(() => { const b = document.querySelector('.op-btn-chat'); if (!b) return null; b.scrollIntoView({block: 'center'}); const r = b.getBoundingClientRect(); return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2}); })()""") log("== 3) 沟通按钮坐标 ==", box) before = {t["id"] for t in lite.list_tabs()} if box: xy = json.loads(box) time.sleep(0.5) box2 = s.eval_js("""(() => { const b = document.querySelector('.op-btn-chat'); const r = b.getBoundingClientRect(); return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2}); })()""") xy = json.loads(box2) s.click_at(int(xy["x"]), int(xy["y"])) time.sleep(5) after = lite.list_tabs() new_tabs = [t for t in after if t["id"] not in before and t["id"] != tab["id"]] log("== 4) 可信点击后新标签 ==", [(t.get("url")) for t in new_tabs]) if new_tabs: c = Session(new_tabs[0]["webSocketDebuggerUrl"]) time.sleep(3) r5 = c.eval_js("""(() => { const ta = document.querySelector('textarea'); const sendBtn = document.querySelector('.chat-input .btn-send, .btn-send'); const sends = [...document.querySelectorAll('a,button,div')] .filter(e => (e.innerText || '').trim() === '发送' && e.offsetHeight > 0) .map(e => ({tag: e.tagName, cls: e.className})); return JSON.stringify({url: location.href, taClass: ta ? ta.className : null, inChatInput: ta ? !!ta.closest('.chat-input') : false, sendBtnClass: sendBtn ? sendBtn.className : null, sends: sends.slice(0, 5)}); })()""") log("== 5) 聊天页结构 ==", r5) c.close() lite.close_tab(new_tabs[0]["id"]) s.close() lite.close_tab(tab["id"]) log("== DONE ==") print("probe8 done ->", OUT) if __name__ == "__main__": main()