utils-seleniumxp 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1112 @@
1
+ # Selenium webdriver utilities - XP version
2
+ # webdriver class - additional functionalities
3
+
4
+ """
5
+ module with webdriver class extensions
6
+
7
+ Webdriver extensions include:
8
+ - speed-up for finding elements using parsel
9
+ - access to shadow dom (with translation of xpath to css)
10
+ - helper closing pop-ups
11
+ - wait functions
12
+ """
13
+
14
+
15
+ # ruff and mypy per file settings
16
+ #
17
+ # empty lines
18
+ # ruff: noqa: E302, E303
19
+ # naming conventions
20
+ # ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
21
+ # boolean-type arguments
22
+ # ruff: noqa: FBT001, FBT002
23
+ # others
24
+ # ruff: noqa: B010, E301, E305, E501, PLR0904, PLR0914, PLR0917, PLR1702, PLR5501, S101, SIM102
25
+ #
26
+ # disable mypy errors
27
+ # mypy: disable-error-code = "no-any-return, attr-defined, unused-ignore"
28
+
29
+ # fmt: off
30
+
31
+
32
+
33
+ # TODO Dev:
34
+ # - more comfortable wait_for
35
+ # params element, condition, timeout
36
+ # - find_element_frames -> loop across frames automatically?
37
+ # - integrate new Selenium 4.x API functions
38
+ # - scroll from Actions-API (instead of script calling)
39
+ # see https://www.selenium.dev/documentation/webdriver/actions_api/wheel/
40
+ # - automatic retry for find_element(s) (see seleniumbase as inspiration) ?
41
+ # approach 1: derived class with redefinition and call of super-method
42
+ # approach 2: create wrapped method and re-direct call via setattr
43
+ # - implement additional helpers like automated findwait_for_element, download (see horejsek wrapper or selgym)
44
+ # alternatively: derived class with redefinition and call of super method?
45
+
46
+ # TODO Test:
47
+ # - n. a.
48
+
49
+
50
+
51
+ from typing import Optional, Union
52
+ from collections.abc import Generator
53
+
54
+ import contextlib
55
+
56
+ import time
57
+ import fnmatch # alternative: simplematch
58
+
59
+ # import queue
60
+ import collections
61
+
62
+ import cssify
63
+ from seleniumrequests.request import RequestsSessionMixin as _RequestsSessionMixin
64
+
65
+ import utils_seleniumxp
66
+
67
+
68
+
69
+ # block direct calling
70
+ # __all__ = []
71
+
72
+
73
+
74
+ # webdriver mixins approach - require Mixin classes to be used for additional functionality
75
+ # mixin-class required per browser specific webdriver class
76
+ # optional: use setattr (assumption: derived wrapper classes should automatically inherit methods)
77
+
78
+ # mixin object for normal webdriver
79
+ class _WebDriverMixin:
80
+ """
81
+ _WebDriverMixin - mixin class with extensions
82
+ """
83
+
84
+ # call __init__ of base class to avoid it is ignored due to mixin MRO
85
+ def __init__(self, *args, **kwargs):
86
+ super().__init__(*args, **kwargs)
87
+
88
+ # mixin for get_user_agent
89
+ def get_user_agent(self) -> str:
90
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
91
+ return get_user_agent(self)
92
+
93
+ # mixin for is_present / is_element_present
94
+
95
+ def is_present(self, by: utils_seleniumxp.By, value: str, use_parsel: bool = True) -> bool:
96
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
97
+ return is_present(self, by, value, use_parsel)
98
+
99
+ def is_element_present(self, by: utils_seleniumxp.By, value: str, use_parsel: bool = True) -> bool:
100
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
101
+ return is_present(self, by, value, use_parsel)
102
+
103
+ # mixin for find_elements_optimized
104
+ def find_elements_optimized(
105
+ self, by: utils_seleniumxp.By, value: str, use_parsel: bool = True
106
+ ) -> list[utils_seleniumxp._WebElement]:
107
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
108
+ return find_elements_optimized(self, by, value, use_parsel)
109
+
110
+ # mixin for find_shadowroot, find_elements_shadowdom and find_element_shadowdom
111
+
112
+ def find_root_shadowdom(self, by: utils_seleniumxp.By, value: str) -> Optional[utils_seleniumxp._ShadowRoot]:
113
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
114
+ return find_root_shadowdom(self, by, value)
115
+
116
+ def find_elements_shadowdom_simple(
117
+ self, by: utils_seleniumxp.By, value: str, shadowroot: Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]
118
+ ) -> Optional[list[utils_seleniumxp._WebElement]]:
119
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
120
+ return find_elements_shadowdom_simple(self, by, value, shadowroot)
121
+
122
+ def find_elements_shadowdom(
123
+ self, locator_list: list[utils_seleniumxp.SeleniumLocator], shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
124
+ ) -> Optional[list[utils_seleniumxp._WebElement]]:
125
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
126
+ return find_elements_shadowdom(self, locator_list, shadowroot)
127
+
128
+ def find_element_shadowdom_simple(
129
+ self, by: utils_seleniumxp.By, value: str, shadowroot: Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]
130
+ ) -> Optional[utils_seleniumxp._WebElement]:
131
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
132
+ return find_element_shadowdom_simple(self, by, value, shadowroot)
133
+
134
+ def find_element_shadowdom(
135
+ self, locator_list: list[utils_seleniumxp.SeleniumLocator], shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
136
+ ) -> Optional[utils_seleniumxp._WebElement]:
137
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
138
+ return find_element_shadowdom(self, locator_list, shadowroot)
139
+
140
+ # mixin for is_present_shadowdom
141
+
142
+ def is_present_shadowdom(
143
+ self, locator_list: list[utils_seleniumxp.SeleniumLocator], shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
144
+ ) -> bool:
145
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
146
+ return is_present_shadowdom(self, locator_list, shadowroot)
147
+
148
+ def is_element_present_shadowdom(
149
+ self, locator_list: list[utils_seleniumxp.SeleniumLocator], shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
150
+ ) -> bool:
151
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
152
+ return is_element_present_shadowdom(self, locator_list, shadowroot)
153
+
154
+ # mixin for hover over element
155
+ def hover_over_element(
156
+ self, by: utils_seleniumxp.By, value: str, by_host: Optional[utils_seleniumxp.By], value_host: Optional[str]
157
+ ) -> None:
158
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
159
+ hover_over_element(self, by, value, by_host, value_host)
160
+
161
+ # mixin for handle_alert
162
+ def handle_alert(self, alerttext: str, accept: bool = False) -> bool:
163
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
164
+ return handle_alert(self, alerttext, accept)
165
+
166
+ # mixin for closepopup routines
167
+
168
+ def closepopup(
169
+ self,
170
+ locator_click: utils_seleniumxp.SeleniumLocator,
171
+ wait_click: float,
172
+ check_click: bool = False,
173
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
174
+ wait_iframe: float = 1,
175
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
176
+ ) -> bool:
177
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
178
+ return closepopup(self, locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost)
179
+
180
+ def closepopup_queueadd(
181
+ self,
182
+ locator_click: utils_seleniumxp.SeleniumLocator,
183
+ wait_click: float,
184
+ check_click: bool = False,
185
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
186
+ wait_iframe: float = 1,
187
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
188
+ ) -> None:
189
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
190
+ closepopup_queueadd(self, locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost)
191
+
192
+ def closepopup_queueprocessing(self, firstonly: bool = True) -> bool:
193
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
194
+ return closepopup_queueprocessing(self, firstonly)
195
+
196
+ # mixin for closewindows
197
+ def closewindows(self, keepwindows: list) -> None:
198
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
199
+ closewindows(self, keepwindows)
200
+
201
+ # mixin for wait4AJAX and wait4HTMLstable
202
+
203
+ def wait4AJAX(self, timeout: int = 15, min_wait: float = 0.0) -> bool:
204
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
205
+ return wait4AJAX(self, timeout, min_wait)
206
+
207
+ def wait4HTMLstable(self, wait: float = 0.1, max_wait: float = 0.5) -> bool:
208
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
209
+ return wait4HTMLstable(self, wait, max_wait)
210
+
211
+ # extended wait for page load - source from ObeytheTestingGoat
212
+ def wait_for_page_load(self, timeout=10) -> contextlib.AbstractContextManager:
213
+ assert isinstance(self, utils_seleniumxp._RemoteWebDriver)
214
+ return wait_for_page_load(self, timeout)
215
+
216
+
217
+ # mixin overlay for 3rd party extensions always mixed in
218
+ def WebDriverMixedinOnly3rdParty(
219
+ cls_webdriver: type[utils_seleniumxp._RemoteWebDriver]
220
+ ) -> type[utils_seleniumxp._RemoteWebDriver]:
221
+ """
222
+ WebDriverMixedinOnly3rdParty - factory function for custom class with fixed 3rd party mixins
223
+
224
+ The factory function mechanism is required to use alternative base classes like
225
+ undetected_chromedriver.
226
+
227
+ Args:
228
+ cls_webdriver (type[utils_seleniumxp._RemoteWebDriver]): base class
229
+
230
+ Returns:
231
+ type[utils_seleniumxp._RemoteWebDriver]: custom webdriver class with mixin
232
+ """
233
+
234
+ # class WebDriverClassCustom(_RequestsSessionMixin, cls_webdriver):
235
+ # pass
236
+ #
237
+ # return WebDriverClassCustom
238
+ return type("WebDriverMixedinOnly3rdParty", (cls_webdriver, _RequestsSessionMixin), {})
239
+
240
+ # own mixin overlay
241
+ def WebDriverMixedin(
242
+ cls_webdriver: type[utils_seleniumxp._RemoteWebDriver]
243
+ ) -> type[utils_seleniumxp._RemoteWebDriver]:
244
+ """
245
+ WebDriverMixedin - factory function for custom class with fixed 3rd party mixins and own mixin
246
+
247
+ The factory function mechanism is required to use alternative base classes like
248
+ undetected_chromedriver.
249
+
250
+ Args:
251
+ cls_webdriver (type[utils_seleniumxp._RemoteWebDriver]): base class
252
+
253
+ Returns:
254
+ type[utils_seleniumxp._RemoteWebDriver]: custom webdriver class with mixin
255
+ """
256
+
257
+ # class WebDriverClassCustom(_WebDriverMixin, _RequestsSessionMixin, cls_webdriver):
258
+ # pass
259
+ #
260
+ # return WebDriverClassCustom
261
+ return type("WebDriverMixedin", (cls_webdriver, _RequestsSessionMixin, _WebDriverMixin), {})
262
+
263
+ # mixin class for eventfiring webdriver
264
+ class EventFiringWebDriverExtendedMixedin(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended): # docsig: disable
265
+ """
266
+ EventFiringWebDriverExtendedMixedin - mixin class for eventfiring webdriver
267
+ """
268
+
269
+ # mixin for closepopup routines
270
+
271
+ def closepopup(
272
+ self,
273
+ locator_click: utils_seleniumxp.SeleniumLocator,
274
+ wait_click: float,
275
+ check_click: bool = False,
276
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
277
+ wait_iframe: float = 1,
278
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
279
+ ) -> bool:
280
+ return closepopup_eventfiring(self, locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost)
281
+
282
+ def closepopup_queueadd(
283
+ self, locator_click:
284
+ utils_seleniumxp.SeleniumLocator,
285
+ wait_click: float,
286
+ check_click: bool = False,
287
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
288
+ wait_iframe: float = 1,
289
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
290
+ ) -> bool:
291
+ return closepopup_queueadd_eventfiring(self, locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost)
292
+
293
+ def closepopup_queueprocessing(self, firstonly: bool = True) -> bool:
294
+ return closepopup_queueprocessing_eventfiring(self, firstonly)
295
+
296
+
297
+
298
+ # user agent
299
+
300
+ # get user agent via JavaScript
301
+ def get_user_agent(webdriver: utils_seleniumxp._RemoteWebDriver) -> str:
302
+ """
303
+ get_user_agent - get user agent via javascript
304
+
305
+ Args:
306
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
307
+
308
+ Returns:
309
+ str: user agent string
310
+ """
311
+ return webdriver.execute_script("return navigator.userAgent")
312
+
313
+ # direct settattr instead of mixin-object but avoid name conflict
314
+ if not utils_seleniumxp.mixinactive:
315
+ setattr(utils_seleniumxp._RemoteWebDriver, "get_user_agent", get_user_agent)
316
+
317
+
318
+ # element present
319
+
320
+ # check if element is present
321
+ def is_present(
322
+ webdriver: utils_seleniumxp._RemoteWebDriver,
323
+ by: utils_seleniumxp.By,
324
+ value: str,
325
+ use_parsel: bool = True
326
+ ) -> bool:
327
+ """
328
+ is_present - check if webelement is present
329
+
330
+ If element is not present, the standard routine is pretty time-consuming compared to parsel
331
+ using C implemented lxml library. The overhead caused by the library is comparably slow.
332
+ However, parsel can only be used for XPATH and CSS.
333
+
334
+ Args:
335
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
336
+ by (utils_seleniumxp.By): locator type
337
+ value (str): locator value
338
+ use_parsel (bool, optional): flag to use parsel. Defaults to True.
339
+
340
+ Returns:
341
+ bool: flag if element is present or not
342
+ """
343
+
344
+ if use_parsel and by in {utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR}:
345
+ parsedhtml = utils_seleniumxp.locatorutils.parselSelectorExtension(text=webdriver.page_source)
346
+ return len(parsedhtml.css_or_xpath(utils_seleniumxp.SeleniumLocator(by, value)).getall()) > 0
347
+ else:
348
+ # alternative variant -> as slow as try-variant if not present (even slightly slower in case element is present)
349
+ # but potentially more errors if descriptor is not unique
350
+ # return len(webdriver.find_elements(by, value)) > 0
351
+ try:
352
+ webdriver.find_element(by, value)
353
+ except Exception:
354
+ return False
355
+ else:
356
+ return True
357
+
358
+ def is_element_present(
359
+ webdriver: utils_seleniumxp._RemoteWebDriver,
360
+ by: utils_seleniumxp.By,
361
+ value: str,
362
+ use_parsel: bool = True
363
+ ) -> bool:
364
+ """
365
+ is_element_present - check if webelement is present (alternative caller vor _is_present)
366
+ """
367
+ return is_present(webdriver, by, value, use_parsel)
368
+
369
+ # direct settattr instead of mixin-object but avoid name conflict
370
+ # (not relevant for EventFiringWebDriver)
371
+ if not utils_seleniumxp.mixinactive:
372
+ setattr(utils_seleniumxp._RemoteWebDriver, "is_present", is_present)
373
+ setattr(utils_seleniumxp._RemoteWebDriver, "is_element_present", is_present)
374
+
375
+
376
+ # find elements - optimized if not present
377
+
378
+ # find elements optimized
379
+ def find_elements_optimized(
380
+ webdriver: utils_seleniumxp._RemoteWebDriver,
381
+ by: utils_seleniumxp.By,
382
+ value: str,
383
+ use_parsel: bool = True
384
+ ) -> list[utils_seleniumxp._WebElement]:
385
+ """
386
+ find_elements_optimized - optimized find_elements using parsel
387
+
388
+ Args:
389
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
390
+ by (utils_seleniumxp.By): locator type
391
+ value (str): locator value
392
+ use_parsel (bool, optional): flag to use parsel. Defaults to True.
393
+
394
+ Returns:
395
+ list[utils_seleniumxp._WebElement]: list of webelements matching locator
396
+ """
397
+
398
+ if use_parsel and by in {utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR}:
399
+ if webdriver.is_present(by, value, use_parsel):
400
+ return webdriver.find_elements(by, value)
401
+ else:
402
+ return []
403
+ else:
404
+ return webdriver.find_elements(by, value)
405
+
406
+ # direct settattr instead of mixin-object but avoid name conflict
407
+ # (not relevant for EventFiringWebDriver)
408
+ if not utils_seleniumxp.mixinactive:
409
+ setattr(utils_seleniumxp._RemoteWebDriver, "find_elements_optimized", find_elements_optimized)
410
+
411
+
412
+ # find elements in shadow DOM
413
+
414
+ # Note:
415
+ # - remember to escape quotes in CSS selectors
416
+ # - when integrating into event firing webdriver watch out due to recursive call like for closepopup
417
+ # - *_simple functions/methods are stubs for overhauled old logic
418
+
419
+ # find shadow DOM root
420
+ def find_root_shadowdom(
421
+ webdriver: utils_seleniumxp._RemoteWebDriver,
422
+ by: utils_seleniumxp.By,
423
+ value: str
424
+ ) -> Optional[utils_seleniumxp._ShadowRoot]:
425
+ """
426
+ find_root_shadowdom - find shadowDOM root
427
+
428
+ Args:
429
+ webdriver (utils_seleniumxp._RemoteWebDriver): browser
430
+ by (utils_seleniumxp.By): locator type of element hosting shadowDOM root
431
+ value (str): locator value of element hosting shadowDOM root
432
+
433
+ Returns:
434
+ Optional[utils_seleniumxp._WebElement]: shadowDOM root if found
435
+ """
436
+
437
+ shadowhost = webdriver.find_element(by, value)
438
+ shadowroot = webdriver.execute_script("return arguments[0].shadowRoot", shadowhost)
439
+ return shadowroot
440
+
441
+ # find elements in shadow DOM old/simple version
442
+ def find_elements_shadowdom_simple(
443
+ webdriver: utils_seleniumxp._RemoteWebDriver,
444
+ by: utils_seleniumxp.By,
445
+ value: str,
446
+ shadowroot: Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]
447
+ ) -> Optional[list[utils_seleniumxp._WebElement]]:
448
+ """
449
+ find_elements_shadowdom_simple - find elements in shadowDOM
450
+
451
+ Args:
452
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
453
+ by (utils_seleniumxp.By): locator type
454
+ value (str): locator value
455
+ shadowroot (Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]): shadowDOM root
456
+
457
+ Returns:
458
+ Optional[utils_seleniumxp._WebElement]: list of webelements in shadowDOM if found
459
+ """
460
+ return find_elements_shadowdom(webdriver, [utils_seleniumxp.SeleniumLocator(by, value)], shadowroot)
461
+
462
+ # find elements in shadow DOM with support for nested DOM - with root as optional parameter
463
+ def find_elements_shadowdom(
464
+ webdriver: utils_seleniumxp._RemoteWebDriver,
465
+ locator_list: list[utils_seleniumxp.SeleniumLocator],
466
+ shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
467
+ ) -> Optional[list[utils_seleniumxp._WebElement]]:
468
+ """
469
+ find_elements_shadowdom - find elements in shadowDOM with support for nested shadowDOM
470
+
471
+ Note: every item in the locator list must be a locator to a host of another shadowDOM root.
472
+ The routine also accepts the shadowhost element and derives the shadowroot automatically.
473
+
474
+ Args:
475
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
476
+ locator_list (list[utils_seleniumxp.SeleniumLocator]): locator list
477
+ shadowroot (Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]], optional): shadowDOM root. Defaults to None.
478
+
479
+ Returns:
480
+ Optional[list[utils_seleniumxp._WebElement]]: list of webelements in shadowDOM if found
481
+ """
482
+
483
+ def prepare_selector(locator: utils_seleniumxp.SeleniumLocator) -> str:
484
+
485
+ if locator.by == utils_seleniumxp.By.XPATH:
486
+ return cssify.cssify(locator.value)
487
+ elif locator.by == utils_seleniumxp.By.CSS_SELECTOR:
488
+ return locator.value
489
+ else:
490
+ err_msg = "Only CSS selector allowed together with element in shadowDOM."
491
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
492
+
493
+ if len(locator_list) > 1 or shadowroot is not None:
494
+ queryselector = ""
495
+ for i in range(0, len(locator_list) - 1):
496
+ queryselector = queryselector + ".querySelector('" + prepare_selector(locator_list[i]) + "').shadowRoot"
497
+ queryselector = queryselector + ".querySelectorAll('" + prepare_selector(locator_list[-1]) + "')"
498
+ if shadowroot is not None:
499
+ if shadowroot.__class__.__name__ != "ShadowRoot":
500
+ # overcome issue that ShadwoDOM host but not root is provided
501
+ # try to treat shadowroot as host to derive correct root
502
+ try:
503
+ shadowroot = webdriver.execute_script("return arguments[0].shadowRoot", shadowroot)
504
+ except Exception:
505
+ return None
506
+ # overcome issue with id attribute, discovered missing in JSON return when accessing shadow root in May 2025
507
+ if not hasattr(shadowroot, "id"):
508
+ shadowroot.id = shadowroot._id # type: ignore[misc]
509
+ try:
510
+ return webdriver.execute_script(f"return arguments[0]{queryselector}", shadowroot)
511
+ except Exception:
512
+ return None
513
+ else:
514
+ try:
515
+ return webdriver.execute_script(f"return document{queryselector}")
516
+ except Exception:
517
+ return None
518
+ else:
519
+ err_msg = "No sufficient selector information provided to access element in shadowDOM."
520
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
521
+
522
+ # find element in shadow DOM old/simple version
523
+ def find_element_shadowdom_simple(
524
+ webdriver: utils_seleniumxp._RemoteWebDriver,
525
+ by: utils_seleniumxp.By,
526
+ value: str,
527
+ shadowroot: Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]
528
+ ) -> Optional[utils_seleniumxp._WebElement]:
529
+ """
530
+ find_element_shadowdom_simple - find element in shadowDOM
531
+
532
+ Args:
533
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
534
+ by (utils_seleniumxp.By): locator type
535
+ value (str): locator value
536
+ shadowroot (Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]): shadowDOM root
537
+
538
+ Returns:
539
+ Optional[utils_seleniumxp._WebElement]: webelement in shadowDOM if found
540
+ """
541
+ return find_element_shadowdom(webdriver, [utils_seleniumxp.SeleniumLocator(by, value)], shadowroot)
542
+
543
+ # find element in shadow DOM with support for nested DOM - with top root as optional parameter
544
+ def find_element_shadowdom(
545
+ webdriver: utils_seleniumxp._RemoteWebDriver,
546
+ locator_list: list[utils_seleniumxp.SeleniumLocator],
547
+ shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
548
+ ) -> Optional[utils_seleniumxp._WebElement]:
549
+ """
550
+ find_element_shadowdom - find element in shadowDOM with support for nested shadowDOM
551
+
552
+ Note: every item in the locator list must be a locator to a host of another shadowDOM root.
553
+
554
+ Args:
555
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
556
+ locator_list (list[utils_seleniumxp.SeleniumLocator]): locator list
557
+ shadowroot (Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]], optional): shadowDOM root. Defaults to None.
558
+
559
+ Returns:
560
+ Optional[utils_seleniumxp._WebElement]: webelement in shadowDOM if found
561
+ """
562
+
563
+ webelts = find_elements_shadowdom(webdriver, locator_list, shadowroot)
564
+ if webelts is not None and webelts != []:
565
+ if len(webelts) == 1:
566
+ return webelts[0]
567
+ else:
568
+ err_msg = "Multiple elements for descriptor in shadow DOM"
569
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
570
+ else:
571
+ return None
572
+
573
+ # check if element present in shadow DOM with support for nested DOM - top root as optional parameter
574
+ def is_present_shadowdom(
575
+ webdriver: utils_seleniumxp._RemoteWebDriver,
576
+ locator_list: list[utils_seleniumxp.SeleniumLocator],
577
+ shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
578
+ ) -> bool:
579
+ """
580
+ is_present_shadowdom - check if element is present in shadowDOM
581
+
582
+ Note: every item in the locator list must be a locator to a host of another shadowDOM root.
583
+
584
+ Args:
585
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
586
+ locator_list (list[utils_seleniumxp.SeleniumLocator]): locator list
587
+ shadowroot (Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]], optional): shadowDOM root. Defaults to None.
588
+
589
+ Returns:
590
+ bool: flag if element is present or not
591
+ """
592
+
593
+ webelts = find_elements_shadowdom(webdriver, locator_list, shadowroot)
594
+ return webelts is not None and webelts != []
595
+
596
+ def is_element_present_shadowdom(
597
+ webdriver: utils_seleniumxp._RemoteWebDriver,
598
+ locator_list: list[utils_seleniumxp.SeleniumLocator],
599
+ shadowroot: Optional[Union[utils_seleniumxp._ShadowRoot, utils_seleniumxp._WebElement]] = None
600
+ ) -> bool:
601
+ """
602
+ is_element_present_shadowdom - check if element is present in shadowDOM (alternative caller for is_present_shadowdom)
603
+ """
604
+ return is_present_shadowdom(webdriver, locator_list, shadowroot)
605
+
606
+ # direct settattr instead of mixin-object but avoid name conflict
607
+ # (not relevant for EventFiringWebDriver)
608
+ if not utils_seleniumxp.mixinactive:
609
+ setattr(utils_seleniumxp._RemoteWebDriver, "find_root_shadowdom", find_root_shadowdom)
610
+ setattr(utils_seleniumxp._RemoteWebDriver, "find_elements_shadowdom_simple", find_elements_shadowdom_simple)
611
+ setattr(utils_seleniumxp._RemoteWebDriver, "find_elements_shadowdom", find_elements_shadowdom)
612
+ setattr(utils_seleniumxp._RemoteWebDriver, "find_element_shadowdom_simple", find_element_shadowdom_simple)
613
+ setattr(utils_seleniumxp._RemoteWebDriver, "find_element_shadowdom", find_element_shadowdom)
614
+ setattr(utils_seleniumxp._RemoteWebDriver, "is_present_shadowdom", is_present_shadowdom)
615
+ setattr(utils_seleniumxp._RemoteWebDriver, "is_element_present_shadowdom", is_present_shadowdom)
616
+
617
+
618
+ # hover over element
619
+
620
+ # hover over element
621
+ def hover_over_element(
622
+ webdriver: utils_seleniumxp._RemoteWebDriver,
623
+ by: utils_seleniumxp.By,
624
+ value: str,
625
+ by_host: Optional[utils_seleniumxp.By],
626
+ value_host: Optional[str]
627
+ ) -> None:
628
+ """
629
+ hover_over_element - action chain to hover over element
630
+
631
+ Args:
632
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
633
+ by (utils_seleniumxp.By): locator type
634
+ value (str): locator value
635
+ by_host (utils_seleniumxp.By, optional): locator type of shadowhost. Defaults to None.
636
+ value_host (str, optional): locator value of shadowhost. Defaults to None.
637
+ """
638
+
639
+ if value_host is None:
640
+ if webdriver.is_present(by, value):
641
+ webelement = webdriver.find_element(by, value)
642
+ else:
643
+ shadowroot = webdriver.find_root_shadowdom(by_host, value_host)
644
+ webelement = webdriver.find_element_shadowdom_simple(by, value, shadowroot)
645
+ utils_seleniumxp.WebDriver.ActionChains(webdriver).move_to_element(webelement).perform()
646
+
647
+ # direct settattr instead of mixin-object but avoid name conflict
648
+ # (not relevant for EventFiringWebDriver)
649
+ if not utils_seleniumxp.mixinactive:
650
+ setattr(utils_seleniumxp._RemoteWebDriver, "hover_over_element", hover_over_element)
651
+
652
+
653
+ # alert handling
654
+
655
+ # alert handler including check of alert text
656
+ def handle_alert(webdriver: utils_seleniumxp._RemoteWebDriver, alerttext: str, accept: bool = False) -> bool:
657
+ """
658
+ handle_alert - handle alert
659
+
660
+ Args:
661
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
662
+ alerttext (str): alert text
663
+ accept (bool, optional): accept yes or no. Defaults to False.
664
+
665
+ Returns:
666
+ bool: flag if alert was processed successfully or not
667
+ """
668
+
669
+ if utils_seleniumxp.ExpectedConditions.alert_is_present(): # type: ignore[truthy-function]
670
+ try:
671
+ alert = webdriver._switch_to.alert
672
+ alertmatch = (not alerttext or fnmatch.fnmatch(alert.text, "*" + alerttext + "*"))
673
+ if alertmatch:
674
+ if accept:
675
+ alert.accept()
676
+ else:
677
+ alert.dismiss()
678
+ return True
679
+ else:
680
+ return False
681
+ except utils_seleniumxp.WebDriverExceptions.NoAlertPresentException:
682
+ return False
683
+ else:
684
+ return False
685
+
686
+ # direct settattr instead of mixin-object but avoid name conflict
687
+ if not utils_seleniumxp.mixinactive:
688
+ setattr(utils_seleniumxp._RemoteWebDriver, "handle_alert", handle_alert)
689
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "handle_alert", handle_alert)
690
+
691
+
692
+ # close popups - processing via a queue to speed up subsequent tries to close popups via html parsing
693
+ #
694
+ # note: when using shadow DOM ist seems CSS is mandatory at least for end nodes
695
+ # see https://github.com/SeleniumHQ/selenium/issues/4971
696
+
697
+ # close popup using parsel for XPath and CSS
698
+ def closepopup(
699
+ webdriver: utils_seleniumxp._RemoteWebDriver,
700
+ locator_click: utils_seleniumxp.SeleniumLocator,
701
+ wait_click: float = 0.1, check_click: bool = False,
702
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
703
+ wait_iframe: float = 1,
704
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
705
+ ) -> bool:
706
+ """
707
+ closepopup - close popups with use of parsel
708
+
709
+ Args:
710
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
711
+ locator_click (utils_seleniumxp.SeleniumLocator): locator for webelement to lcick for closing
712
+ wait_click (float, optional): wait after click. DEfaults to 0.1.
713
+ check_click (bool, optional): check after click if popup closed. Defaults to False.
714
+ locator_iframe (utils_seleniumxp.SeleniumLocator, optional): locator for iframe containing click object. Defaults to None.
715
+ wait_iframe (float, optional): wait to switch to iframe. Defaults to 1.
716
+ locator_shadowdomhost (utils_seleniumxp.SeleniumLocator, optional): locator to shadowDOM host. Defaults to None.
717
+
718
+ Returns:
719
+ bool: flag if a matching popup was found and closed
720
+ """
721
+
722
+ closepopup_queueadd(webdriver, locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost)
723
+ return closepopup_queueprocessing(webdriver)
724
+
725
+ # closepopup - queue request
726
+ def closepopup_queueadd(
727
+ webdriver: utils_seleniumxp._RemoteWebDriver,
728
+ locator_click: utils_seleniumxp.SeleniumLocator,
729
+ wait_click: float = 0.1, check_click: bool = False,
730
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
731
+ wait_iframe: float = 1,
732
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
733
+ ) -> None:
734
+ """
735
+ closepopup_queueadd - add entry to closepopop processing queue
736
+
737
+ Args:
738
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
739
+ locator_click (utils_seleniumxp.SeleniumLocator): locator for webelement to lcick for closing
740
+ wait_click (float, optional): wait after click. DEfaults to 0.1.
741
+ check_click (bool, optional): check after click if popup closed. Defaults to False.
742
+ locator_iframe (utils_seleniumxp.SeleniumLocator, optional): locator for iframe containing click object. Defaults to None.
743
+ wait_iframe (float, optional): wait to switch to iframe. Defaults to 1.
744
+ locator_shadowdomhost (utils_seleniumxp.SeleniumLocator, optional): locator to shadowDOM host. Defaults to None.
745
+ """
746
+
747
+ # check if webdriver has queue attribute already
748
+ if hasattr(webdriver, 'closepopup_queue'):
749
+ pass
750
+ else:
751
+ closepopup_queue = collections.deque() # type: ignore[var-annotated]
752
+ setattr(webdriver, 'closepopup_queue', closepopup_queue)
753
+
754
+ # add to queue
755
+ queueentry = {
756
+ "locator_click": locator_click,
757
+ "wait_click": wait_click,
758
+ "check_click": check_click,
759
+ "locator_iframe": locator_iframe,
760
+ "wait_iframe": wait_iframe,
761
+ "locator_shadowdomhost": locator_shadowdomhost
762
+ }
763
+ webdriver.closepopup_queue.append(queueentry)
764
+
765
+ # closepopup - queue processing
766
+ def closepopup_queueprocessing(webdriver: utils_seleniumxp._RemoteWebDriver, firstonly: bool = True) -> bool:
767
+ """
768
+ closepopup_queueprocessing - process closepopup queue
769
+
770
+ Args:
771
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
772
+ firstonly (bool, optional): process first found target webelement only. Defaults to True.
773
+
774
+ Returns:
775
+ bool: flag if a matching popup was found and closed
776
+ """
777
+
778
+ # set return default
779
+ closedpopup: bool = False
780
+
781
+ if hasattr(webdriver, 'closepopup_queue'):
782
+
783
+ if len(webdriver.closepopup_queue) > 0:
784
+ webdriver.wait4AJAX()
785
+ parsedhtml = utils_seleniumxp.locatorutils.parselSelectorExtension(text=webdriver.page_source)
786
+
787
+ while len(webdriver.closepopup_queue) > 0:
788
+
789
+ webdriver.wait4AJAX()
790
+ queueentry = webdriver.closepopup_queue.popleft()
791
+
792
+ locator_click = queueentry["locator_click"]
793
+ wait_click = queueentry["wait_click"]
794
+ check_click = queueentry["check_click"]
795
+ locator_iframe = queueentry["locator_iframe"]
796
+ wait_iframe = queueentry["wait_iframe"]
797
+ locator_shadowdomhost = queueentry["locator_shadowdomhost"]
798
+
799
+ if not firstonly or not closedpopup:
800
+
801
+ # convert locator within shadowDOM to CSS
802
+ if locator_shadowdomhost is not None:
803
+ if locator_click.by == utils_seleniumxp.By.XPATH:
804
+ locator_click = utils_seleniumxp.SeleniumLocator(utils_seleniumxp.By.CSS_SELECTOR, cssify.cssify(locator_click.value))
805
+ elif locator_click.by != utils_seleniumxp.By.CSS_SELECTOR:
806
+ utils_seleniumxp.ErrorUtilsSelenium("Only CSS selector allowed together with element in shadowDOM.")
807
+
808
+ # initialize parsedhtml at beginning of loop
809
+ parsedhtml = utils_seleniumxp.locatorutils.parselSelectorExtension(text=webdriver.page_source)
810
+
811
+ # go to frame of popup (if any)
812
+ if locator_iframe is not None:
813
+ if utils_seleniumxp.locatorutils.check_locator(locator_iframe, [utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR]):
814
+ frames = parsedhtml.css_or_xpath(locator_iframe).getall()
815
+ # re-parse once, sometimes timing problem -> caused by switch-to error
816
+ if len(frames) == 0:
817
+ parsedhtml = utils_seleniumxp.locatorutils.parselSelectorExtension(text=webdriver.page_source)
818
+ frames = parsedhtml.css_or_xpath(locator_iframe).getall()
819
+ else:
820
+ frames = webdriver.find_elements(*locator_iframe)
821
+ if len(frames) == 0:
822
+ if hasattr(webdriver, "closepopup_logger"):
823
+ webdriver.closepopup_logger.info(f"FRAME not found\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
824
+ continue
825
+ elif len(frames) == 1:
826
+ utils_seleniumxp.WebDriverWait(webdriver, wait_iframe).until(utils_seleniumxp.ExpectedConditions.frame_to_be_available_and_switch_to_it(locator_iframe))
827
+ if (utils_seleniumxp.locatorutils.check_locator(locator_click, [utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR]) or
828
+ utils_seleniumxp.locatorutils.check_locator(locator_shadowdomhost, [utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR])
829
+ ):
830
+ parsedhtml = utils_seleniumxp.locatorutils.parselSelectorExtension(text=webdriver.page_source)
831
+ elif len(frames) > 1:
832
+ if hasattr(webdriver, "closepopup_logger"):
833
+ webdriver.closepopup_logger.info(f"FRAME not unique\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
834
+ continue
835
+
836
+ # find close popup (considering also shadow DOM webelements)
837
+ if locator_shadowdomhost is not None:
838
+ if utils_seleniumxp.locatorutils.check_locator(locator_shadowdomhost, [utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR]):
839
+ shadowhosts = parsedhtml.css_or_xpath(locator_shadowdomhost).getall()
840
+ # re-parse once, sometimes timing problem
841
+ if len(shadowhosts) == 0:
842
+ parsedhtml = utils_seleniumxp.locatorutils.parselSelectorExtension(text=webdriver.page_source)
843
+ shadowhosts = parsedhtml.css_or_xpath(locator_shadowdomhost).getall()
844
+ else:
845
+ shadowhosts = webdriver.find_elements(*locator_shadowdomhost)
846
+ if len(shadowhosts) == 0:
847
+ webelts = []
848
+ if hasattr(webdriver, "closepopup_logger"):
849
+ webdriver.closepopup_logger.info(f"ShadowDOM host not found\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
850
+ continue
851
+ elif len(shadowhosts) == 1:
852
+ shadowhost = webdriver.find_element(*locator_shadowdomhost)
853
+ shadowroot = webdriver.execute_script("return arguments[0].shadowRoot", shadowhost)
854
+ webelts = shadowroot.find_elements(*locator_click)
855
+ else:
856
+ webelts = []
857
+ if hasattr(webdriver, "closepopup_logger"):
858
+ webdriver.closepopup_logger.info(f"ShadowDOM host not unique\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
859
+ continue
860
+ else:
861
+ if utils_seleniumxp.locatorutils.check_locator(locator_click, {utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR}):
862
+ webelts = parsedhtml.css_or_xpath(locator_click).getall()
863
+ webelts = webdriver.find_elements(*locator_click) if len(webelts) > 0 else []
864
+ else:
865
+ webelts = webdriver.find_elements(*locator_click)
866
+
867
+ # close popup
868
+ if len(webelts) > 0:
869
+
870
+ closedpopup_thisrun = False
871
+ for webelt in webelts:
872
+ try:
873
+ if webelt.is_displayed() and not webelt.is_overlapped(): # type: ignore[union-attr]
874
+ countwindows = len(webdriver.window_handles)
875
+ keepwindows = webdriver.window_handles
876
+ webelt.click()
877
+ if wait_click > 0:
878
+ time.sleep(wait_click)
879
+ if len(webdriver.window_handles) > countwindows:
880
+ closewindows(webdriver, keepwindows)
881
+ closedpopup = True
882
+ closedpopup_thisrun = True
883
+ if hasattr(webdriver, "closepopup_logger"):
884
+ webdriver.closepopup_logger.info(f"found target\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
885
+ break
886
+ except utils_seleniumxp.WebDriverExceptions.StaleElementReferenceException:
887
+ pass # simple rerun
888
+ except utils_seleniumxp.WebDriverExceptions.ElementClickInterceptedException:
889
+ pass # simple rerun
890
+ except:
891
+ raise
892
+
893
+ if check_click and closedpopup_thisrun:
894
+ if locator_shadowdomhost is not None:
895
+ webelts = shadowroot.find_elements(*locator_click)
896
+ else:
897
+ if utils_seleniumxp.locatorutils.check_locator(locator_click, {utils_seleniumxp.By.XPATH, utils_seleniumxp.By.CSS_SELECTOR}):
898
+ webelts = parsedhtml.css_or_xpath(locator_click).getall()
899
+ webelts = webdriver.find_elements(*locator_click) if len(webelts) > 0 else []
900
+ else:
901
+ webelts = webdriver.find_elements(*locator_click)
902
+ for webelt in webelts:
903
+ if webelt.is_displayed():
904
+ err_msg = "Popup could not be closed."
905
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
906
+
907
+ else:
908
+ if hasattr(webdriver, "closepopup_logger"):
909
+ webdriver.closepopup_logger.info(f"not found\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
910
+
911
+ # switch back from frame if necessary
912
+ if locator_iframe is not None:
913
+ if len(frames) != 0:
914
+ webdriver.switch_to.default_content()
915
+
916
+ else:
917
+ if hasattr(webdriver, "closepopup_logger"):
918
+ webdriver.closepopup_logger.info(f"not checked\t{webdriver.current_url}\t({locator_click})\t({locator_iframe})\t({locator_shadowdomhost})")
919
+
920
+ return closedpopup
921
+
922
+ # direct settattr instead of mixin-object but avoid name conflict
923
+ if not utils_seleniumxp.mixinactive:
924
+ setattr(utils_seleniumxp._RemoteWebDriver, "closepopup", closepopup)
925
+ setattr(utils_seleniumxp._RemoteWebDriver, "closepopup_queueadd", closepopup_queueadd)
926
+ setattr(utils_seleniumxp._RemoteWebDriver, "closepopup_queueprocessing", closepopup_queueprocessing)
927
+
928
+
929
+ # closepopup methods for EventFiringWebDriver
930
+ #
931
+ # note:
932
+ # - as closepopup methods are not elementary methods i.e. other event firing methods are called, a special
933
+ # treatment for "recursive" calling is required
934
+ # - as closepopup_queueadd creates a new attribute (the queue), when using EventFiringWebDriverExtended it must be
935
+ # taken care that the attribute is created and accessed on same class level i.e. event firing driver class or
936
+ # wrapped driver class level -> implementation prevents methods/calls marked as "recursive" on event firing
937
+ # driver class level to be dispatched down to wrapped class level
938
+
939
+ def closepopup_eventfiring(
940
+ webdriver: utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended,
941
+ locator_click: utils_seleniumxp.SeleniumLocator,
942
+ wait_click: float,
943
+ check_click: bool = False,
944
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
945
+ wait_iframe: float = 1,
946
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
947
+ ) -> bool:
948
+ """
949
+ closepopup_eventfiring - closepopup for eventfiring webdriver, required to avoid endless recurion loop)
950
+ """
951
+ return webdriver._dispatch("closepopuphandler", ("simpleclose", webdriver._driver), "_closepopup", (locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost), b_recursive=True)
952
+
953
+ def closepopup_queueadd_eventfiring(
954
+ webdriver: utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended,
955
+ locator_click: utils_seleniumxp.SeleniumLocator,
956
+ wait_click: float, check_click: bool = False,
957
+ locator_iframe: Optional[utils_seleniumxp.SeleniumLocator] = None,
958
+ wait_iframe: float = 1,
959
+ locator_shadowdomhost: Optional[utils_seleniumxp.SeleniumLocator] = None
960
+ ) -> bool:
961
+ """
962
+ closepopup_queueadd_eventfiring - closepopup_queueadd for eventfiring webdriver, required to avoid endless recurion loop)
963
+ """
964
+ return webdriver._dispatch(None, (), "_closepopup_queueadd", (locator_click, wait_click, check_click, locator_iframe, wait_iframe, locator_shadowdomhost), b_recursive=True)
965
+
966
+ def closepopup_queueprocessing_eventfiring(
967
+ webdriver: utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended,
968
+ firstonly: bool = True
969
+ ) -> bool:
970
+ """
971
+ closepopup_queueprocessing_eventfiring - closepopup_queueprocessing for eventfiring webdriver, required to avoid endless recurion loop)
972
+ """
973
+ return webdriver._dispatch("closepopuphandler", ("queueprocessing", webdriver._driver), "_closepopup_queueprocessing", (firstonly,), b_recursive=True)
974
+
975
+ # direct settattr instead of mixin-object but avoid name conflict
976
+ if not utils_seleniumxp.mixinactive:
977
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "closepopup", closepopup_eventfiring)
978
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "closepopup_queueadd", closepopup_queueadd_eventfiring)
979
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "closepopup_queueprocessing", closepopup_queueprocessing_eventfiring)
980
+ # shadow routines to overcome recursion issue, inherited by EventFiringWebDriverExtended_Mixin
981
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "_closepopup", closepopup)
982
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "_closepopup_queueadd", closepopup_queueadd)
983
+ setattr(utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended, "_closepopup_queueprocessing", closepopup_queueprocessing)
984
+
985
+
986
+ # close new windows opened automatically f. e. by downloads
987
+
988
+ # close new windows opened by automatic downloads, ...
989
+ # note: transfer value for parameter keepwindows as list even if a single handle !!!
990
+ def closewindows(webdriver: utils_seleniumxp._RemoteWebDriver, keepwindows: list) -> None:
991
+ """
992
+ closewindows - close windows except those in 'keeplist'
993
+
994
+ Args:
995
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
996
+ keepwindows (list): list with windows to keep
997
+ """
998
+
999
+ keepcount: int = len(keepwindows)
1000
+ if keepcount == 0:
1001
+ return
1002
+
1003
+ while len(webdriver.window_handles) > keepcount:
1004
+ for handle in reversed(webdriver.window_handles):
1005
+ if handle not in keepwindows:
1006
+ webdriver.switch_to.window(handle)
1007
+ webdriver.close()
1008
+ break
1009
+
1010
+ # direct settattr instead of mixin-object but avoid name conflict
1011
+ if not utils_seleniumxp.mixinactive:
1012
+ setattr(utils_seleniumxp._RemoteWebDriver, "closewindows", closewindows)
1013
+
1014
+
1015
+ # extended wait for page load - readyState + AJAX-script
1016
+
1017
+ # wait for AJAX script and readyState
1018
+ # first check if jQuery is active
1019
+ def wait4AJAX(webdriver: utils_seleniumxp._RemoteWebDriver, timeout: int = 10, min_wait: float = 0.5) -> bool:
1020
+ """
1021
+ wait4AJAX - wait routine checking jQuery.active via JavaScript and document.readyState
1022
+
1023
+ Args:
1024
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
1025
+ timeout (int): timeout
1026
+ min_wait (float, optional): minimum wait time. Defaults to 0.5.
1027
+
1028
+ Returns:
1029
+ bool: flag if timeout reached
1030
+ """
1031
+
1032
+ starttime = time.time()
1033
+ timeoutscript = False
1034
+ try:
1035
+ utils_seleniumxp.WebDriverWait(webdriver, 1).until(lambda webdriver: webdriver.execute_script('return jQuery.active') == 0)
1036
+ except (utils_seleniumxp.WebDriverExceptions.JavascriptException, utils_seleniumxp.WebDriverExceptions.TimeoutException):
1037
+ pass
1038
+ else:
1039
+ try:
1040
+ utils_seleniumxp.WebDriverWait(webdriver, timeout).until(lambda webdriver: webdriver.execute_script('return jQuery.active') == 0)
1041
+ except utils_seleniumxp.WebDriverExceptions.TimeoutException:
1042
+ timeoutscript = True
1043
+
1044
+ timeoutdocrs = False
1045
+ try:
1046
+ utils_seleniumxp.WebDriverWait(webdriver, timeout).until(lambda webdriver: webdriver.execute_script('return document.readyState') == 'complete')
1047
+ except utils_seleniumxp.WebDriverExceptions.TimeoutException:
1048
+ timeoutdocrs = True
1049
+
1050
+ while (time.time() < starttime + min_wait):
1051
+ time.sleep(0.1)
1052
+
1053
+ return timeoutscript or timeoutdocrs
1054
+
1055
+ # wait for HTML, AJAX script and readyState
1056
+ def wait4HTMLstable(webdriver: utils_seleniumxp._RemoteWebDriver, wait: float = 0.1, max_wait: float = 0.5) -> bool:
1057
+ """
1058
+ wait4HTMLstable - wait routine checking stability page source
1059
+
1060
+ Args:
1061
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
1062
+ wait (float, optional): wait between re-checks. Defaults to 0.1.
1063
+ max_wait (float, optional): timeout. Defaults to 0.5.
1064
+
1065
+ Returns:
1066
+ bool: flag if page source is stable
1067
+ """
1068
+
1069
+ wait4AJAX(webdriver)
1070
+ HTMLprev = ""
1071
+ starttime = time.time()
1072
+ while (HTMLprev != webdriver.page_source and (time.time() < starttime + max_wait)):
1073
+ HTMLprev = webdriver.page_source
1074
+ time.sleep(wait)
1075
+
1076
+ return HTMLprev == webdriver.page_source
1077
+
1078
+ # direct setattr instead of mixin-object but avoid name conflict
1079
+ if not utils_seleniumxp.mixinactive:
1080
+ setattr(utils_seleniumxp._RemoteWebDriver, "wait4AJAX", wait4AJAX)
1081
+ setattr(utils_seleniumxp._RemoteWebDriver, "wait4HTMLstable", wait4HTMLstable)
1082
+
1083
+
1084
+ # extended wait for page load - source from ObeyTheTestingGoat
1085
+ @contextlib.contextmanager
1086
+ def wait_for_page_load(webdriver: utils_seleniumxp._RemoteWebDriver, timeout=10) -> Generator:
1087
+ """
1088
+ wait_for_page_load - wait routine with contextmanager from ObeyTheTestingGoat
1089
+
1090
+ method checks for the staleness of the old page (i.e., that the new page has loaded)
1091
+ prior to moving forward with further actions. Therefore, it only works in situations
1092
+ where the URL changes between page loads.
1093
+
1094
+ Usage:
1095
+ with self.wait_for_page_load():
1096
+ click a button or do whatever
1097
+ do the next thing that was failing before using this
1098
+
1099
+ Args:
1100
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver
1101
+ timeout (int, optional): timeout. Defaults to 10.
1102
+
1103
+ Return:
1104
+ (Generator): contextmanager generator
1105
+ """
1106
+ old_page = webdriver.find_element(utils_seleniumxp.By.TAG_NAME, 'html')
1107
+ yield
1108
+ utils_seleniumxp.WebDriverWait(webdriver, timeout).until(utils_seleniumxp.ExpectedConditions.staleness_of(old_page))
1109
+
1110
+ # direct setattr instead of mixin-object but avoid name conflict
1111
+ if not utils_seleniumxp.mixinactive:
1112
+ setattr(utils_seleniumxp._RemoteWebDriver, "wait_for_page_load", wait_for_page_load)