"""十二探测:详情页可信点击 btn-startchat 是否开聊天标签 + 聊天页结构""" 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_probe12.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 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") time.sleep(8) s0 = Session(tab["webSocketDebuggerUrl"]) s0.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})); inp.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true})); return true; })()""") time.sleep(5) href = s0.eval_js("(document.querySelector('.job-card-wrap a.job-name') || {getAttribute: () => ''}).getAttribute('href')") s0.close() lite.close_tab(tab["id"]) log("== 1) 职位 ==", href) if not href: log("== DONE ==") return dtab = lite.open_tab("https://www.zhipin.com" + href) time.sleep(6) d = Session(dtab["webSocketDebuggerUrl"]) # 按钮坐标 + elementFromPoint 校验 info = d.eval_js("""(() => { const b = document.querySelector('.btn-startchat'); if (!b) return null; const r = b.getBoundingClientRect(); const x = r.x + r.width / 2, y = r.y + r.height / 2; const top = document.elementFromPoint(x, y); return JSON.stringify({x, y, topCls: top ? top.className : null, topIsBtn: top === b || (top && b.contains(top))}); })()""") log("== 2) 按钮坐标/顶层元素 ==", info) before = {t["id"] for t in lite.list_tabs()} p = json.loads(info) d.click_at(int(p["x"]), int(p["y"])) time.sleep(5) new_tabs = [t for t in lite.list_tabs() if t["id"] not in before and t["id"] != dtab["id"]] log("== 3) 新标签 ==", [t.get("url") for t in new_tabs], " 同页 ==", d.eval_js("location.href")) if new_tabs: c = Session(new_tabs[0]["webSocketDebuggerUrl"]) time.sleep(4) 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("== 4) 聊天页 ==", r5) c.close() lite.close_tab(new_tabs[0]["id"]) d.close() lite.close_tab(dtab["id"]) log("== DONE ==") print("probe12 done ->", OUT) if __name__ == "__main__": main()