92 lines
3.2 KiB
Python
92 lines
3.2 KiB
Python
from PyQt6.QtCore import Qt, QTimer
|
|
|
|
|
|
class ActionService:
|
|
"""
|
|
Service mô phỏng hành động người dùng trong QWebEngineView
|
|
bằng JavaScript (click, gõ, nhấn phím), KHÔNG chiếm quyền chuột.
|
|
"""
|
|
|
|
def __init__(self, webview=None, delay=0.05):
|
|
"""
|
|
webview: QWebEngineView để thao tác
|
|
delay: thời gian nghỉ giữa các thao tác (giây)
|
|
"""
|
|
self.webview = webview
|
|
self.delay = delay
|
|
|
|
# ----------------------------------------------------------------------
|
|
def _run_js(self, script: str):
|
|
"""Chạy JavaScript trên webview"""
|
|
if not self.webview:
|
|
print("[WARN] Không có webview để chạy JS.")
|
|
return
|
|
self.webview.page().runJavaScript(script)
|
|
|
|
# ----------------------------------------------------------------------
|
|
def click_center_of_region(self, top_left, bottom_right):
|
|
"""Click bằng JS vào vùng detect"""
|
|
if not self.webview:
|
|
print("[WARN] Không có webview để click.")
|
|
return
|
|
|
|
x = (top_left[0] + bottom_right[0]) // 2
|
|
y = (top_left[1] + bottom_right[1]) // 2
|
|
|
|
script = f"""
|
|
(function() {{
|
|
const el = document.elementFromPoint({x}, {y});
|
|
if (el) {{
|
|
el.focus();
|
|
el.click();
|
|
console.log("Clicked element:", el.tagName);
|
|
}} else {{
|
|
console.log("Không tìm thấy element tại {x},{y}");
|
|
}}
|
|
}})();
|
|
"""
|
|
self._run_js(script)
|
|
|
|
# ----------------------------------------------------------------------
|
|
def write_in_region(self, top_left, bottom_right, text):
|
|
"""Click + gõ text vào vùng detect bằng JS"""
|
|
if not self.webview:
|
|
print("[WARN] Không có webview để gõ text.")
|
|
return
|
|
|
|
x = (top_left[0] + bottom_right[0]) // 2
|
|
y = (top_left[1] + bottom_right[1]) // 2
|
|
safe_text = str(text).replace('"', '\\"')
|
|
|
|
script = f"""
|
|
(function() {{
|
|
const el = document.elementFromPoint({x}, {y});
|
|
if (el) {{
|
|
el.focus();
|
|
el.value = "{safe_text}";
|
|
const inputEvent = new Event('input', {{ bubbles: true }});
|
|
el.dispatchEvent(inputEvent);
|
|
console.log("Gõ text vào:", el.tagName);
|
|
}} else {{
|
|
console.log("Không tìm thấy element tại {x},{y}");
|
|
}}
|
|
}})();
|
|
"""
|
|
self._run_js(script)
|
|
|
|
# ----------------------------------------------------------------------
|
|
def press_key(self, key="Enter"):
|
|
"""Nhấn phím bằng JS"""
|
|
if not self.webview:
|
|
print("[WARN] Không có webview để nhấn phím.")
|
|
return
|
|
|
|
script = f"""
|
|
(function() {{
|
|
const evt = new KeyboardEvent('keydown', {{ key: '{key}', bubbles: true }});
|
|
document.activeElement && document.activeElement.dispatchEvent(evt);
|
|
console.log("Nhấn phím:", '{key}');
|
|
}})();
|
|
"""
|
|
self._run_js(script)
|