Repository navigation
Expand file tree
/
Copy pathBuiltInFunctions.py
More file actions
2058 lines (1846 loc) · 74.7 KB
/
Copy pathBuiltInFunctions.py
File metadata and controls
2058 lines (1846 loc) · 74.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Synchronous Playwright counterparts for ZeuZ Selenium actions."""
import ast
import asyncio
import base64
import functools
import inspect
import json
import socket
import sys
import time
import threading
from pathlib import Path
from urllib.parse import urldefrag, urlparse
from Framework.Built_In_Automation.Shared_Resources import LocateElement
from Framework.Built_In_Automation.Shared_Resources import (
BuiltInFunctionSharedResources as sr,
)
from Framework.Built_In_Automation.Sequential_Actions.action_declarations.playwright import (
declarations,
)
from Framework.Utilities import CommonUtil, ConfigModule
from Framework.Utilities.CommonUtil import failed_tag_list
MODULE_NAME = inspect.getmodulename(__file__)
temp_config = str(
Path(__file__).resolve().parents[4]
/ "AutomationLog"
/ ConfigModule.get_config_value("Advanced Options", "_file")
)
class _BrowserState(threading.local):
"""Keep sync Playwright objects on their action or performance thread."""
def __init__(self):
self.playwright_details = {}
self.playwright_page = None
self.current_driver_id = None
self._playwright = None
_browser_state = _BrowserState()
def _log(message, level=1):
CommonUtil.ExecLog(MODULE_NAME, message, level)
def _fail(message):
_log(message, 3)
return "zeuz_failed"
_DIAGNOSTIC_SNAPSHOT = """element => {
const describe = el => {
if (!el || el.nodeType !== 1) return null;
const info = {};
for (const name of ['id', 'class', 'type', 'role', 'aria-expanded', 'aria-label',
'aria-selected', 'aria-checked', 'aria-busy'])
info[name] = (el.getAttribute(name) || '').slice(0, 200);
info.tag = el.tagName;
if ('checked' in el) info.checked = el.checked;
if ('value' in el && el.type !== 'password') info.value_length = el.value.length;
return info;
};
if (!window.__zeuzPlaywrightDiagnostics) {
const events = [];
window.__zeuzPlaywrightDiagnostics = events;
for (const type of ['pointerdown', 'mousedown', 'mouseup', 'click', 'dblclick', 'focusin', 'focusout', 'input', 'change'])
document.addEventListener(type, event => {
events.push({time: Date.now(), type, target: describe(event.target),
parent: describe(event.target.parentElement),
trusted: event.isTrusted, detail: event.detail,
input_type: event.inputType || null});
if (events.length > 30) events.shift();
}, true);
}
const rect = element ? element.getBoundingClientRect() : null;
const overlays = [...document.querySelectorAll(
'[role="dialog"], [role="listbox"], .p-overlaypanel, .popover'
)].filter(el => el.getClientRects().length && getComputedStyle(el).visibility !== 'hidden');
return {
time: Date.now(), frame: location.origin + location.pathname,
viewport: {width: innerWidth, height: innerHeight, scroll_x: scrollX, scroll_y: scrollY},
target: describe(element), parent: describe(element && element.parentElement),
rect: rect ? rect.toJSON() : null,
hit_at_center: rect ? describe(document.elementFromPoint(
rect.x + rect.width / 2, rect.y + rect.height / 2)) : null,
active: describe(document.activeElement),
hovered: [...document.querySelectorAll(':hover')].slice(-5).map(describe),
overlay_count: overlays.length, overlays: overlays.slice(0, 10).map(describe),
controls: [...document.querySelectorAll(
'input[type="checkbox"], [role="switch"], [aria-busy="true"]'
)].slice(0, 30).map(describe),
events: window.__zeuzPlaywrightDiagnostics
};
}"""
def _diagnostic(stage, element=None):
"""Opt in with zeuz_playwright_diagnostics=true or comma-separated test case IDs."""
try:
setting = str(sr.Get_Shared_Variables("zeuz_playwright_diagnostics", log=False)).strip()
if (setting.lower() not in CommonUtil.affirmative_words
and (not CommonUtil.current_tc_no
or CommonUtil.current_tc_no not in [case.strip() for case in setting.split(",")])):
return
record = {"stage": stage, "case": CommonUtil.current_tc_no,
"step_id": CommonUtil.current_step_id, "step": CommonUtil.current_step_no,
"action": CommonUtil.current_action_no}
if hasattr(element, "evaluate"):
try:
if LocateElement._is_playwright_locator(element):
record["target"] = (element.evaluate(_DIAGNOSTIC_SNAPSHOT, timeout=500)
if element.count() else {"missing": True})
else:
record["target"] = element.evaluate(_DIAGNOSTIC_SNAPSHOT)
box = (element.bounding_box(timeout=500) if LocateElement._is_playwright_locator(element)
else element.bounding_box())
record["main_rect"] = box
if box:
record["main_hit_at_center"] = get_page().evaluate("""point => {
const el = document.elementFromPoint(point.x, point.y);
return el ? {tag: el.tagName, id: el.id, class: el.getAttribute('class')} : null;
}""", {"x": box["x"] + box["width"] / 2, "y": box["y"] + box["height"] / 2})
except Exception as error:
record["target"] = {"unavailable": type(error).__name__}
record["frames"] = []
for frame in get_page().frames:
try:
record["frames"].append(frame.evaluate(_DIAGNOSTIC_SNAPSHOT))
except Exception as error:
record["frames"].append({"unavailable": type(error).__name__})
_log("PW_DIAGNOSTIC " + json.dumps(record, ensure_ascii=False))
except Exception:
# Diagnostics must never change the action result, including during teardown.
pass
def _rows(data_set):
return [
(str(left).strip(), str(middle).strip().lower(), str(right))
for left, middle, right in data_set
]
def _key(value):
return value.replace(" ", "").replace("_", "").replace("-", "").lower()
def _action(data_set, default=""):
return next(
(right for _left, middle, right in _rows(data_set) if "action" in middle),
default,
)
def _driver_id(data_set, default=None):
for left, _middle, right in _rows(data_set):
if _key(left) in ("driverid", "drivertag"):
return right.strip() or "default"
return default or _browser_state.current_driver_id or "default"
def _state():
if _browser_state.current_driver_id not in _browser_state.playwright_details:
raise RuntimeError(
"No active Playwright browser. Run 'open browser' or 'go to link' first."
)
return _browser_state.playwright_details[_browser_state.current_driver_id]
def get_driver():
state = _state()
return state.get("frame") or state["page"]
def get_page():
return _state()["page"]
def get_dom(_data_set=()):
return get_page().evaluate("""() => {
const html = document.documentElement.cloneNode(true);
html.setAttribute('zeuz', 'aiplugin');
html.querySelectorAll('head,link,script,style').forEach(node => node.remove());
return html.outerHTML.replace(/[\\x00-\\x08\\x0B-\\x1F\\x7F]/g, '');
}""")
def _element(data_set, all_elements=False, root=None):
return LocateElement.Get_Element(
data_set, root or get_driver(), return_all_elements=all_elements
)
def _set_active(driver_id):
_browser_state.current_driver_id = driver_id
state = _browser_state.playwright_details[driver_id]
bridge = state.get("selenium_bridge")
if bridge is not None:
session = state["context"].new_cdp_session(state["page"])
try:
target_id = session.send("Target.getTargetInfo")["targetInfo"]["targetId"]
finally:
session.detach()
bridge.switch_to.window(target_id)
_browser_state.playwright_page = state["page"]
sr.Set_Shared_Variables("playwright_page", _browser_state.playwright_page)
sr.Set_Shared_Variables("common_driver", state.get("frame") or _browser_state.playwright_page)
_publish_selenium_bridge(state.get("selenium_bridge"))
sr.Set_Shared_Variables("zeuz_active_browser_backend", "playwright")
owners = sr.Get_Shared_Variables("zeuz_browser_backends", log=False)
owners = owners if isinstance(owners, dict) else {}
owners[driver_id] = "playwright"
sr.Set_Shared_Variables("zeuz_browser_backends", owners)
CommonUtil.set_screenshot_vars(sr.Shared_Variable_Export())
def _publish_selenium_bridge(driver):
from Framework.Built_In_Automation.Web.Selenium import BuiltInFunctions as selenium
selenium.selenium_driver = driver
if driver is None:
sr.Remove_From_Shared_Variables("selenium_driver")
else:
sr.Set_Shared_Variables("selenium_driver", driver)
def _free_local_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def _configured_viewport():
try:
width = int(ConfigModule.get_config_value("RunDefinition", "window_size_x"))
height = int(ConfigModule.get_config_value("RunDefinition", "window_size_y"))
if width > 0 and height > 0:
return {"width": width, "height": height}
except (TypeError, ValueError):
pass
return {"width": 1920, "height": 1080}
def _selenium_cdp_address(browser_name, debugger, arguments):
if not any(name in browser_name for name in ("chrome", "edge", "chromium")):
return None
if debugger:
parsed = urlparse(debugger if "://" in debugger else "//" + debugger)
if not parsed.hostname or not parsed.port:
raise ValueError(f"Invalid debugger address '{debugger}'")
return f"{parsed.hostname}:{parsed.port}"
port = None
for index, argument in enumerate(arguments):
if str(argument).startswith("--remote-debugging-port="):
port = int(str(argument).split("=", 1)[1])
if port == 0:
port = _free_local_port()
arguments[index] = f"--remote-debugging-port={port}"
break
if port is None:
port = _free_local_port()
arguments.extend(
[f"--remote-debugging-port={port}", "--remote-debugging-address=127.0.0.1"]
)
return f"127.0.0.1:{port}"
def _attach_selenium_bridge(state, browser_name, debugger_address, driver_path=None):
if not debugger_address:
state["selenium_bridge"] = None
_log(
"Selenium execute-python compatibility is unavailable for Playwright Firefox/WebKit",
2,
)
return
try:
from selenium import webdriver
if "edge" in browser_name:
from selenium.webdriver.edge.options import Options
options = Options()
options.debugger_address = debugger_address
driver = webdriver.Edge(options=options)
else:
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
options = Options()
options.debugger_address = debugger_address
driver = webdriver.Chrome(
options=options,
service=Service(executable_path=driver_path) if driver_path else None,
)
state["selenium_bridge"] = driver
_log("Attached Selenium compatibility bridge to Playwright browser", 1)
except Exception as error:
state["selenium_bridge"] = None
_log(f"Could not attach Selenium compatibility bridge: {error}", 2)
def _close_selenium_bridge(state):
driver = state.pop("selenium_bridge", None)
if driver is not None:
try:
driver.quit()
except Exception:
_log("Unable to close Selenium compatibility bridge", 2)
def _parse(value):
try:
return CommonUtil.parse_value_into_object(value)
except Exception:
try:
return ast.literal_eval(value)
except Exception:
return value
def _alert_instruction(data_set):
value = _action(data_set).strip()
prompt = next((right.strip() for left, middle, right in _rows(data_set)
if middle == "input parameter" and left.lower() in ("prompt text", "text", "send text")), None)
if _key(value).startswith("sendtext") and "=" in value:
prompt = value.split("=", 1)[1].strip()
return ("dismiss" if value.lower() in ("reject", "decline", "fail", "no", "cancel", "dismiss") else "accept"), prompt
def _next_alert_instruction():
try:
step_data = sr.Get_Shared_Variables("step_data", log=False)
index = int(CommonUtil.current_action_no)
if not isinstance(step_data, list) or index >= len(step_data):
return "dismiss", None
for left, middle, right in _rows(step_data[index]):
if left.lower() == "handle alert" and "action" in middle:
return _alert_instruction(step_data[index])
except Exception:
pass
return "dismiss", None
def _on_dialog(state, dialog):
instruction, prompt = (
_alert_instruction(state["alert_rows"])
if "alert_rows" in state else _next_alert_instruction()
)
state["dialog"] = {
"text": dialog.message,
"type": dialog.type,
"result": instruction,
}
if instruction == "accept":
dialog.accept(prompt)
else:
dialog.dismiss()
def _wire_page(state, page, activate=True):
if activate:
state["page"] = page
state["frame"] = None
state["frame_stack"] = []
wired_pages = state.setdefault("wired_pages", set())
if id(page) in wired_pages:
return
wired_pages.add(id(page))
page.on("dialog", lambda dialog: _on_dialog(state, dialog))
page.on("download", lambda download: state["downloads"].append(download))
if state["capturing_network"]:
_capture_network_page(state, page)
if not state.get("page_listener"):
page.context.on("page", lambda new_page: _wire_page(state, new_page, activate=False))
state["page_listener"] = True
def _launch(data_set):
from playwright.sync_api import Error, sync_playwright
rows = _rows(data_set)
for left, _middle, right in rows:
if _key(left) in ("waittimetoappearelement", "waitforelement"):
sr.Set_Shared_Variables("element_wait", float(right))
dependency = sr.Get_Shared_Variables("dependency")
browser_name = str(dependency.get("Browser", "Chrome")).strip().lower()
if "opera" in browser_name:
raise RuntimeError("Opera is not supported by Playwright")
driver_id = _driver_id(data_set, "default")
if driver_id in _browser_state.playwright_details:
state = _browser_state.playwright_details[driver_id]
page = state["page"]
try:
# A live request also processes close events queued while Python or
# Selenium actions were running outside the Playwright thread.
page.title()
except Error:
browser, context = state["browser"], state["context"]
if not browser.is_connected() or context not in browser.contexts:
Tear_Down_Selenium([("driver id", "optional parameter", driver_id)])
state = None
elif page.is_closed():
pages = [page for page in context.pages if not page.is_closed()]
page = pages[-1] if pages else context.new_page()
_wire_page(state, page)
else:
raise
if state is not None:
_set_active(driver_id)
return state
if _browser_state._playwright is None:
_browser_state._playwright = sync_playwright().start()
headless = "headless" in browser_name
launch = {"headless": headless}
context_options = {"accept_downloads": True, "viewport": _configured_viewport()}
wait_until = "load"
debugger = None
chrome_version = None
chrome_driver_path = None
firefox_prefs = {}
arguments = []
for left, middle, right in rows:
key = _key(left)
value = _parse(right)
if key in ("waittimetopageload", "pageloadtimeout"):
context_options["timeout"] = float(right) * 1000
elif key == "resolution":
width, height = (
int(part.strip())
for part in right.lower().replace("x", ",").split(",", 1)
)
context_options["viewport"] = {"width": width, "height": height}
elif key in ("addargument", "argument"):
supplied = value if isinstance(value, list) else [right]
for argument in supplied:
if "load-extension" in str(argument) and any(
name in browser_name for name in ("chrome", "edge")
):
_log(
"Playwright ignores extension sideloading on branded Chrome/Edge",
2,
)
else:
arguments.append(argument)
elif key == "pageloadstrategy":
wait_until = {
"normal": "load",
"eager": "domcontentloaded",
"none": "commit",
}.get(right.strip().lower(), "load")
elif key == "debuggeraddress":
debugger = right
elif key in ("chromeversion", "chrome:version"):
chrome_version = right.strip()
elif key in ("proxy", "proxyserver"):
context_options["proxy"] = (
value if isinstance(value, dict) else {"server": right}
)
elif key == "locale":
context_options["locale"] = right
elif key in ("useragent", "user-agent"):
context_options["user_agent"] = right
elif key == "permissions":
context_options["permissions"] = (
value
if isinstance(value, list)
else [part.strip() for part in right.split(",")]
)
elif key in ("ignorehttpserrors", "accepthttpscerts"):
context_options["ignore_https_errors"] = (
str(right).lower() in CommonUtil.affirmative_words
)
elif key == "setpreference" and "firefox" in middle:
if isinstance(value, dict):
firefox_prefs.update(value)
elif key in (
"addextension",
"addencodedextension",
"setcapability",
"addexperimentaloption",
):
_log(f"Playwright ignores unsupported Selenium option '{left}'", 2)
elif middle == "shared capability":
_log(f"Playwright ignores unsupported Selenium capability '{left}'", 2)
selenium_cdp_address = _selenium_cdp_address(browser_name, debugger, arguments)
launch["args"] = arguments
if firefox_prefs:
launch["firefox_user_prefs"] = firefox_prefs
state = {
"browser": None,
"context": None,
"page": None,
"frame": None,
"backend": "playwright",
"downloads": [],
"dialog": None,
"network": [],
"capturing_network": False,
"wait_until": wait_until,
"selenium_bridge": None,
}
if debugger:
if not any(name in browser_name for name in ("chrome", "edge", "chromium")):
raise RuntimeError(
"CDP debugger attachment is only supported for Chromium browsers"
)
endpoint = debugger if "://" in debugger else "http://" + debugger
browser = _browser_state._playwright.chromium.connect_over_cdp(endpoint)
context = (
browser.contexts[0]
if browser.contexts
else browser.new_context(**context_options)
)
else:
if "firefox" in browser_name:
browser_type = _browser_state._playwright.firefox
elif "safari" in browser_name or "webkit" in browser_name:
browser_type = _browser_state._playwright.webkit
else:
browser_type = _browser_state._playwright.chromium
if "edge" in browser_name:
launch["channel"] = "msedge"
elif "chrome" in browser_name:
from Framework.Built_In_Automation.Web.Selenium.utils import (
ChromeForTesting,
)
channel = None
if chrome_version and chrome_version.lower() in (
"beta",
"dev",
"canary",
):
channel, chrome_version = chrome_version.capitalize(), None
chrome_bin, chrome_driver = ChromeForTesting().setup_chrome_for_testing(
chrome_version, channel
)
if chrome_bin:
launch["executable_path"] = str(chrome_bin)
chrome_driver_path = str(chrome_driver)
_log(
f"Using Chrome for Testing {chrome_version or channel or 'latest'}",
1,
)
else:
launch["channel"] = "chrome"
else:
launch["channel"] = "chrome"
browser = browser_type.launch(**launch)
context = browser.new_context(
**{key: value for key, value in context_options.items() if key != "timeout"}
)
if "timeout" in context_options:
context.set_default_navigation_timeout(context_options["timeout"])
state["browser"], state["context"] = browser, context
page = context.pages[-1] if context.pages else context.new_page()
_wire_page(state, page)
_attach_selenium_bridge(
state, browser_name, selenium_cdp_address, chrome_driver_path
)
_browser_state.playwright_details[driver_id] = state
_set_active(driver_id)
return state
def Go_To_Link(data_set):
try:
state = _launch(data_set)
_wire_page(state, state["page"])
_set_active(_browser_state.current_driver_id)
url = next(
(
right
for left, _middle, right in _rows(data_set)
if _key(left) in ("gotolink", "gotolinkv2")
),
None,
)
if url:
page = state["page"]
same_document_hash = (
urlparse(url).fragment
and urldefrag(page.url).url == urldefrag(url).url
)
page.goto(url, wait_until=state["wait_until"])
if same_document_hash:
page.reload(wait_until=state["wait_until"])
return "passed"
except Exception:
return CommonUtil.Exception_Handler(
sys.exc_info(), None, "Failed to open Playwright browser"
)
Go_To_Link_V2 = Go_To_Link
def Open_Electron_App(data_set):
from Framework.Built_In_Automation.Web.Selenium import BuiltInFunctions as selenium
return selenium.Open_Electron_App(data_set)
def Tear_Down_Selenium(data_set=()):
try:
requested = (
_driver_id(data_set)
if any(_key(left) in ("driverid", "drivertag") for left, _, _ in _rows(data_set))
else None
)
ids = [requested] if requested else list(_browser_state.playwright_details)
for driver_id in ids:
state = _browser_state.playwright_details.pop(driver_id, None)
if not state:
continue
try:
_stop_network_capture(state)
_close_selenium_bridge(state)
state["context"].close()
finally:
state["browser"].close()
owners = sr.Get_Shared_Variables("zeuz_browser_backends", log=False)
owners = owners if isinstance(owners, dict) else {}
for driver_id in ids:
if owners.get(driver_id) == "playwright":
owners.pop(driver_id, None)
sr.Set_Shared_Variables("zeuz_browser_backends", owners)
if _browser_state.playwright_details:
_set_active(next(iter(_browser_state.playwright_details)))
else:
if _browser_state._playwright is not None:
_browser_state._playwright.stop()
_browser_state._playwright = None
_browser_state.current_driver_id = _browser_state.playwright_page = None
sr.Remove_From_Shared_Variables("playwright_page")
_publish_selenium_bridge(None)
return "passed"
except Exception:
_log("Unable to tear down Playwright browsers", 2)
return "passed"
def Switch_Browser(data_set):
driver_id = _driver_id(data_set, "default")
if driver_id not in _browser_state.playwright_details:
return _fail(f"Driver_id='{driver_id}' not found")
_set_active(driver_id)
return "passed"
def Get_Current_URL(data_set):
name = _action(data_set)
return (
sr.Set_Shared_Variables(name, get_page().url)
if name
else _fail("Missing variable name")
)
def Navigate(data_set):
value = _action(data_set).strip().lower()
page = get_page()
if value == "back":
page.go_back()
elif value == "forward":
page.go_forward()
elif value == "refresh":
page.reload()
else:
return _fail("Only back, forward, and refresh are supported")
return "passed"
def Click_Element(data_set):
element = _element(data_set)
if element in failed_tag_list:
return "zeuz_failed"
_diagnostic("click.target", element)
options = {}
for left, middle, right in _rows(data_set):
if (
middle in ("optional parameter", "optional option")
and _key(left) == "offset"
):
x, y = (float(part) for part in right.split(",", 1))
box = element.bounding_box()
if not box:
return "zeuz_failed"
options["position"] = {
"x": box["width"] / 2 * (1 + x / 100),
"y": box["height"] / 2 * (1 + y / 100),
}
elif _key(left) == "usejs" and right.strip().lower() in CommonUtil.affirmative_words:
# Match Selenium's explicit JS click, including mouse-dependent widgets.
element.evaluate("""element => {
for (const type of ['mousedown', 'mouseup', 'click'])
element.dispatchEvent(new MouseEvent(type, {
bubbles: true, cancelable: true, view: window, buttons: 1
}));
}""")
return "passed"
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
for attempt in range(2):
try:
element.click(**options)
break
except PlaywrightTimeoutError as error:
outside = "outside of the viewport" in str(error)
intercepted = "intercepts pointer events" in str(error)
if (options or not (outside or intercepted)
or not element.is_visible() or not element.is_enabled()):
raise
if outside and attempt == 0:
element.evaluate("el => el.scrollIntoView({block: 'center', inline: 'center'})")
# An iframe-local scroll may leave the outer page unchanged.
# Playwright bounding boxes use main-frame viewport coordinates.
box = element.bounding_box()
if box:
get_page().evaluate("""box => window.scrollBy({
left: box.x + box.width / 2 - window.innerWidth / 2,
top: box.y + box.height / 2 - window.innerHeight / 2,
behavior: 'instant'
})""", box)
_log("Requested parent-page scroll for offscreen target; retrying the click", 2)
_diagnostic("click.repositioned", element)
continue
# Match Selenium's intercepted-click fallback, not unrelated timeouts.
if not intercepted:
raise
element.evaluate("element => element.click()")
_log("Element click was intercepted; clicked the element using JavaScript", 2)
break
return "passed"
def Click_and_Download(data_set):
timeout = (
next(
(
float(right)
for left, _, right in _rows(data_set)
if _key(left) == "waitfordownload"
),
20,
)
* 1000
)
path = next(
(
CommonUtil.path_parser(right)
for left, middle, right in _rows(data_set)
if _key(left) in ("folderpath", "directory", "filepath", "file", "folder")
and middle.startswith("optional")
),
None,
)
with get_page().expect_download(timeout=timeout) as info:
result = Click_Element(data_set)
if result in failed_tag_list:
return result
download = info.value
if path:
destination = Path(path)
if destination.is_dir() or not destination.suffix:
destination.mkdir(parents=True, exist_ok=True)
destination /= download.suggested_filename
else:
destination.parent.mkdir(parents=True, exist_ok=True)
download.save_as(str(destination))
return "passed"
def Right_Click_Element(data_set):
element = _element(data_set)
if element in failed_tag_list:
return "zeuz_failed"
element.click(button="right")
return "passed"
def Double_Click_Element(data_set):
element = _element(data_set)
if element in failed_tag_list:
return "zeuz_failed"
_diagnostic("double_click.target", element)
element.dblclick()
return "passed"
def Hover_Over_Element(data_set):
element = _element(data_set)
if element in failed_tag_list:
return "zeuz_failed"
element.hover()
return "passed"
_KEYS = {
"CTRL": "Control",
"CONTROL": "Control",
"CMD": "Meta",
"COMMAND": "Meta",
"ALT": "Alt",
"SHIFT": "Shift",
"ENTER": "Enter",
"RETURN": "Enter",
"ESC": "Escape",
"ESCAPE": "Escape",
"TAB": "Tab",
"SPACE": "Space",
"BACKSPACE": "Backspace",
"DELETE": "Delete",
"HOME": "Home",
"END": "End",
"PAGEUP": "PageUp",
"PAGEDOWN": "PageDown",
"UP": "ArrowUp",
"DOWN": "ArrowDown",
"LEFT": "ArrowLeft",
"RIGHT": "ArrowRight",
}
def Keystroke_For_Element(data_set):
field, value = next(
(
(left.lower(), right)
for left, middle, right in _rows(data_set)
if "action" in middle
),
("", ""),
)
element = (
_element(data_set)
if any("element parameter" in middle for _, middle, _ in _rows(data_set))
else None
)
keyboard = get_page().keyboard
if element in failed_tag_list:
return "zeuz_failed"
if "chars" in field:
_type_text(element, value)
else:
key, _, count = value.partition(",")
combo = "+".join(
_KEYS.get(_key(part).upper(), part.strip()) for part in key.split("+")
)
paste_image = any(_key(left) == "pasteimage" and right.strip().lower() == "true"
for left, _, right in _rows(data_set))
if paste_image and combo.lower() in ("control+v", "meta+v"):
combo = "Meta+v" if get_page().evaluate("/Mac/.test(navigator.platform)") else "Control+v"
try:
if element:
element.focus()
keyboard.press(combo)
except Exception:
import pyperclip
text = pyperclip.paste()
if element:
element.evaluate("(el, text) => { el.focus(); el.value = text; }", text)
else:
get_page().evaluate("text => { document.activeElement.value += text; }", text)
return "passed"
for _ in range(int(count or 1)):
element.press(combo) if element else keyboard.press(combo)
return "passed"
def _type_text(element, value, delay=0):
if delay or not value:
(element if element is not None else get_page().keyboard).type(value, delay=delay)
return
if element is None:
keyboard = get_page().keyboard
else:
element.type("") # Preserve native typing's focus and caret placement.
page = element.page if LocateElement._is_playwright_locator(element) else element.owner_frame().page
keyboard = page.keyboard
async def send_keys():
commands = []
for char in value:
# Match Playwright's US-layout keys and insertText for other characters.
if " " <= char <= "~" or char in "\n\r":
commands.extend((keyboard._impl_obj.down(char), keyboard._impl_obj.up(char)))
else:
commands.append(keyboard._impl_obj.insert_text(char))
commands = [asyncio.create_task(command) for command in commands]
# Reuse the action's call site; collecting a stack per key delays dispatch.
for command in commands:
command.__pw_stack_trace__ = asyncio.current_task().__pw_stack_trace__
results = await asyncio.gather(*commands, return_exceptions=True)
for result in results:
if isinstance(result, BaseException):
raise result
# Queue native events like ChromeDriver send_keys, without per-event round trips.
# ponytail: sync/async bridge uses Playwright internals; replace when a public
# batched-key API exists. Browser event-parity tests cover dependency upgrades.
keyboard._sync(keyboard._impl_obj._channel._connection.wrap_api_call(send_keys))
def Enter_Text_In_Text_Box(data_set):
element = _element(data_set)
if element in failed_tag_list:
return "zeuz_failed"
_diagnostic("text.target", element)
value = _action(data_set)
if (element.get_attribute("type") or "").lower() == "file":
element.set_input_files(CommonUtil.path_parser(value))
return "passed"
if any(_key(left) == "usejs" and right.strip().lower() in ("true", "yes", "1")
for left, _, right in _rows(data_set)):
element.evaluate("""(el, value) => {
el.click();
el.value = value;
el.dispatchEvent(new Event('input', {bubbles: true}));
el.dispatchEvent(new Event('change', {bubbles: true}));
el.click();
}""", value)
return "passed"
append = any(
_key(left) == "append" and right.strip().lower() in CommonUtil.affirmative_words
for left, _, right in _rows(data_set)
)
clear = not any(
_key(left) == "clear" and right.strip().lower() in ("no", "false")
for left, _, right in _rows(data_set)
)
delay = next(
(float(right) * 1000 for left, _, right in _rows(data_set) if _key(left) == "delay"),
0,
)
if not 0 <= delay < float("inf"):
return _fail("Typing delay must be a finite, non-negative number of seconds")
# Clicking/clearing can change attributes used by the locator (e.g. ng-pristine).
from playwright.sync_api import Error as PlaywrightError, TimeoutError as PlaywrightTimeoutError
handle = element.element_handle()
try:
try:
handle.click(timeout=5000)
except PlaywrightTimeoutError:
_log("Entering text without clicking the element", 2)
if clear and not append:
try:
handle.press("ControlOrMeta+A")
handle.press("Delete")
if handle.evaluate("el => el.isContentEditable ? el.textContent : el.value"):
handle.fill("")
except PlaywrightError:
pass # Selenium treats clearing as best effort before send_keys.
else:
handle.press("ControlOrMeta+End")
_type_text(handle, value, delay=delay)
try:
handle.click(timeout=5000)
except PlaywrightError:
pass # Match Selenium's best-effort click after typing.
finally:
handle.dispose()
return "passed"
def Validate_Text(data_set):
element = _element(data_set)
if element in failed_tag_list:
return "zeuz_failed"
name, expected = next(
(
(left.lower(), right)
for left, middle, right in _rows(data_set)
if "action" in middle
),
("", ""),
)
actual = element.inner_text().strip()
ignore_case = any(
_key(left) == "ignorecase" and right.strip().lower() in CommonUtil.affirmative_words
for left, _, right in _rows(data_set)
)
if ignore_case: