基本完成
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
"""十三探测:点击事件是否到达 handler + 点击后全部网络请求/弹窗"""
|
||||
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_probe13.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")
|
||||
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"])
|
||||
|
||||
dtab = lite.open_tab("https://www.zhipin.com" + href)
|
||||
time.sleep(6)
|
||||
d = Session(dtab["webSocketDebuggerUrl"])
|
||||
d.call("Network.enable")
|
||||
|
||||
# 挂点击计数监听
|
||||
d.eval_js("""(() => {
|
||||
window.__clicks = 0;
|
||||
const b = document.querySelector('.btn-startchat');
|
||||
if (b) b.addEventListener('click', e => { window.__clicks++; window.__lastTrusted = e.isTrusted; });
|
||||
return !!b;
|
||||
})()""")
|
||||
|
||||
xy = d.eval_js("""(() => {
|
||||
const b = document.querySelector('.btn-startchat');
|
||||
const r = b.getBoundingClientRect();
|
||||
return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2});
|
||||
})()""")
|
||||
p = json.loads(xy)
|
||||
d.click_at(int(p["x"]), int(p["y"]))
|
||||
|
||||
reqs: list[str] = []
|
||||
for msg in d.pump(5):
|
||||
if msg.get("method") == "Network.responseReceived":
|
||||
u = msg["params"]["response"]["url"]
|
||||
if "/wapi/" in u or "chat" in u:
|
||||
reqs.append(f"{msg['params']['response']['status']} {u[:140]}")
|
||||
log("== 1) 点击计数/trusted ==", d.eval_js("JSON.stringify({c: window.__clicks, t: window.__lastTrusted})"))
|
||||
log("== 2) 点击后请求 ==", reqs)
|
||||
log("== 3) 弹窗/toast ==", d.eval_js("""(() => {
|
||||
const els = [...document.querySelectorAll('.toast, .dialog-container, [class*="toast"], [class*="dialog"]')]
|
||||
.filter(e => e.offsetHeight > 0);
|
||||
return JSON.stringify(els.map(e => ({cls: e.className.slice(0, 60), txt: (e.innerText || '').slice(0, 100)})));
|
||||
})()""")
|
||||
log("== 4) 同页URL ==", d.eval_js("location.href"))
|
||||
|
||||
d.close()
|
||||
lite.close_tab(dtab["id"])
|
||||
log("== DONE ==")
|
||||
print("probe13 done ->", OUT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user