-
Notifications
You must be signed in to change notification settings - Fork 509
/
__init__.py
1061 lines (827 loc) · 31.7 KB
/
__init__.py
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
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import os
import re
import tempfile
import time
from contextlib import contextmanager
from typing import Optional
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC # NOQA: N812
from selenium.webdriver.support.ui import WebDriverWait
from splinter.driver import DriverAPI
from splinter.driver import ElementAPI
from splinter.driver.find_links import FindLinks
from splinter.driver.webdriver.cookie_manager import CookieManager
from splinter.driver.xpath_utils import _concat_xpath_from_str
from splinter.element_list import ElementList
from splinter.exceptions import ElementDoesNotExist
from splinter.retry import _retry
# Patch contextmanager onto Selenium's Alert
def alert_enter(self):
return self
def alert_exit(self, type, value, traceback): # NOQA: A002
pass
Alert.__enter__ = alert_enter
Alert.__exit__ = alert_exit
Alert.fill_with = Alert.send_keys
class switch_window: # NOQA: N801
def __init__(self, browser, window_handle):
self.browser = browser
self.window_handle = window_handle
def __enter__(self):
self.current_window_handle = self.browser.driver.current_window_handle
self.browser.driver.switch_to.window(self.window_handle)
def __exit__(self, type, value, traceback): # NOQA: A002
if self.current_window_handle in self.browser.driver.window_handles:
self.browser.driver.switch_to.window(self.current_window_handle)
class Window:
"""A class representing a browser window"""
def __init__(self, browser, name):
self._browser = browser
self.name = name
@property
def title(self):
"""The title of this window"""
with switch_window(self._browser, self.name):
return self._browser.title
@property
def url(self):
"""The url of this window"""
with switch_window(self._browser, self.name):
return self._browser.url
@property
def index(self):
"""The index of this window in browser.windows"""
return self._browser.driver.window_handles.index(self.name)
@property
def prev(self):
"""Return the previous window"""
prev_index = self.index - 1
prev_handle = self._browser.driver.window_handles[prev_index]
return Window(self._browser, prev_handle)
@property # NOQA: A003
def next(self): # NOQA: A003
"""Return the next window"""
next_index = (self.index + 1) % len(self._browser.driver.window_handles)
next_handle = self._browser.driver.window_handles[next_index]
return Window(self._browser, next_handle)
def is_current():
doc = "Whether this window is currently the browser's active window."
def fget(self):
return self._browser.driver.current_window_handle == self.name
def fset(self, value):
if value is True:
self._browser.driver.switch_to.window(self.name)
else:
raise TypeError("can only set to True")
return locals()
is_current = property(**is_current())
def new_tab(self, url):
"""Open new tab in current window"""
if self._browser.driver.name == "firefox":
self._browser.driver.get("about:config")
self._browser.driver.execute_script(
'document.getElementById("warningButton").click();',
)
self._browser.driver.execute_script(
"""
Components.classes['@mozilla.org/preferences-service;1']
.getService(Components.interfaces.nsIPrefBranch)
.setIntPref('browser.link.open_newwindow', 3);
""",
)
self._browser.driver.execute_script("window.open('%s', '_blank');" % url)
if self._browser.driver.name == "firefox":
self._browser.driver.execute_script(
"""
Components.classes['@mozilla.org/preferences-service;1']
.getService(Components.interfaces.nsIPrefBranch)
.setIntPref('browser.link.open_newwindow', 2);
""",
)
self._browser.driver.back()
def close(self):
"""Close this window. If this window is active, switch to previous window"""
target = self.prev if (self.is_current and self.prev != self) else None
with switch_window(self._browser, self.name):
self._browser.driver.close()
if target is not None:
target.is_current = True
def close_others(self):
self.is_current = True
for window in self._browser.windows:
if window != self:
window.close()
def __eq__(self, other):
return self._browser == other._browser and self.name == other.name
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return f"<Window {self.name}: {self.url}>"
class Windows:
"""A class representing all open browser windows"""
def __init__(self, browser):
self._browser = browser
def __len__(self):
return len(self._browser.driver.window_handles)
def __getitem__(self, key):
window_handles = self._browser.driver.window_handles
try:
return Window(self._browser, window_handles[key])
except TypeError:
if key not in window_handles:
raise KeyError(key)
return Window(self._browser, key)
def current():
doc = "The currently active window"
def fget(self):
current_handle = self._browser.driver.current_window_handle
return Window(self._browser, current_handle) if current_handle else None
def fset(self, value):
self._browser.driver.switch_to.window(value.name)
return locals()
current = property(**current())
def __repr__(self):
return str(
[Window(self._browser, handle) for handle in self._browser.driver.window_handles],
)
def _find(self, finder, finder_kwargs=None):
"""Search for elements. Returns a list of results.
Arguments:
finder: The function to use for the element search.
finder_kwargs: Keyword Arguments for the finder function.
Returns:
list
"""
finder_kwargs = finder_kwargs or {}
elements = None
elem_list = []
try:
elements = finder(**finder_kwargs)
if not isinstance(elements, list):
elements = [elements]
except (
NoSuchElementException,
StaleElementReferenceException,
):
# This exception is sometimes thrown if the page changes
# quickly
pass
if elements:
elem_list = [self.element_class(element, self, finder_kwargs) for element in elements]
return elem_list
def find_by(
self,
finder,
finder_kwargs=None,
original_find: str = None,
original_query: str = None,
wait_time: int = None,
):
"""Wrapper for finding elements.
Must be attached to a class.
Returns:
ElementList
"""
elem_list = []
find_by = original_find or finder_kwargs["by"]
query = original_query or finder_kwargs.get("value")
# Zero second wait time means only check once
if wait_time == 0:
elem_list = _find(self, finder, finder_kwargs)
else:
wait_time = wait_time or self.wait_time
end_time = time.time() + wait_time
while time.time() < end_time:
elem_list = _find(self, finder, finder_kwargs)
if elem_list:
break
return ElementList(elem_list, find_by=find_by, query=query)
class BaseWebDriver(DriverAPI):
driver = None
find_by = find_by
def __init__(self, driver=None, wait_time=2):
self.wait_time = wait_time
self.links = FindLinks(self)
self.driver = driver
self._find_elements = self.driver.find_elements
self.element_class = WebDriverElement
self._cookie_manager = CookieManager(self.driver)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.quit()
@property
def title(self):
return self.driver.title
@property
def html(self):
return self.driver.page_source
@property
def url(self):
return self.driver.current_url
@property
def status_code(self):
raise NotImplementedError
def visit(self, url):
self.driver.get(url)
def back(self):
self.driver.back()
def forward(self):
self.driver.forward()
def reload(self):
self.driver.refresh()
def execute_script(self, script, *args):
return self.driver.execute_script(script, *args)
def evaluate_script(self, script, *args):
return self.driver.execute_script("return %s" % script, *args)
def is_element_present(self, finder, selector, wait_time=None):
wait_time = wait_time or self.wait_time
end_time = time.time() + wait_time
while time.time() < end_time:
if finder(selector, wait_time=wait_time):
return True
return False
def is_element_not_present(self, finder, selector, wait_time=None):
wait_time = wait_time or self.wait_time
end_time = time.time() + wait_time
while time.time() < end_time:
if not finder(selector, wait_time=0):
return True
return False
def is_element_present_by_css(self, css_selector, wait_time=None):
return self.is_element_present(self.find_by_css, css_selector, wait_time)
def is_element_not_present_by_css(self, css_selector, wait_time=None):
return self.is_element_not_present(self.find_by_css, css_selector, wait_time)
def is_element_present_by_xpath(self, xpath, wait_time=None):
return self.is_element_present(self.find_by_xpath, xpath, wait_time)
def is_element_not_present_by_xpath(self, xpath, wait_time=None):
return self.is_element_not_present(self.find_by_xpath, xpath, wait_time)
def is_element_present_by_tag(self, tag, wait_time=None):
return self.is_element_present(self.find_by_tag, tag, wait_time)
def is_element_not_present_by_tag(self, tag, wait_time=None):
return self.is_element_not_present(self.find_by_tag, tag, wait_time)
def is_element_present_by_name(self, name, wait_time=None):
return self.is_element_present(self.find_by_name, name, wait_time)
def is_element_not_present_by_name(self, name, wait_time=None):
return self.is_element_not_present(self.find_by_name, name, wait_time)
def is_element_present_by_value(self, value, wait_time=None):
return self.is_element_present(self.find_by_value, value, wait_time)
def is_element_not_present_by_value(self, value, wait_time=None):
return self.is_element_not_present(self.find_by_value, value, wait_time)
def is_element_present_by_text(self, text, wait_time=None):
return self.is_element_present(self.find_by_text, text, wait_time)
def is_element_not_present_by_text(self, text, wait_time=None):
return self.is_element_not_present(self.find_by_text, text, wait_time)
def is_element_present_by_id(self, id, wait_time=None): # NOQA: A002
return self.is_element_present(self.find_by_id, id, wait_time)
def is_element_not_present_by_id(self, id, wait_time=None): # NOQA: A002
return self.is_element_not_present(self.find_by_id, id, wait_time)
def get_alert(self, wait_time=None):
wait_time = wait_time or self.wait_time
try:
alert = WebDriverWait(self.driver, wait_time).until(EC.alert_is_present())
return alert
except TimeoutException:
return None
def _is_text_present(self, text):
try:
self.find_by_tag("body").text.index(text)
return True
except (NoSuchElementException, StaleElementReferenceException, ValueError):
# NoSuchElementException will be thrown if the body tag isn't present
# Can occur if the page isn't fully loaded yet.
# StaleElementReferenceException will be thrown if the page changes quickly
pass
return False
def is_text_present(self, text, wait_time=None):
wait_time = wait_time or self.wait_time
end_time = time.time() + wait_time
while time.time() < end_time:
if self._is_text_present(text):
return True
return False
def is_text_not_present(self, text, wait_time=None):
wait_time = wait_time or self.wait_time
end_time = time.time() + wait_time
while time.time() < end_time:
if not self._is_text_present(text):
return True
return False
@contextmanager
def get_iframe(self, frame_reference):
# If a WebDriverElement is provided, send the underlying element
if isinstance(frame_reference, WebDriverElement):
frame_reference = frame_reference._element
self.driver.switch_to.frame(frame_reference)
try:
yield self
finally:
self.driver.switch_to.frame(None)
def find_option_by_value(self, value):
return self.find_by_xpath(
'//option[@value="%s"]' % value,
original_find="option by value",
original_query=value,
)
def find_option_by_text(self, text):
return self.find_by_xpath(
'//option[normalize-space(text())="%s"]' % text,
original_find="option by text",
original_query=text,
)
def find_by_css(self, css_selector, wait_time=None):
return self.find_by(
self.driver.find_elements,
finder_kwargs={"by": By.CSS_SELECTOR, "value": css_selector},
original_find="css",
original_query=css_selector,
wait_time=wait_time,
)
def find_by_xpath(
self,
xpath,
original_find="xpath",
original_query=None,
wait_time=None,
):
original_query = original_query or xpath
return self.find_by(
self.driver.find_elements,
finder_kwargs={"by": By.XPATH, "value": xpath},
original_find=original_find,
original_query=original_query,
wait_time=wait_time,
)
def find_by_name(self, name, wait_time=None):
return self.find_by(
self.driver.find_elements,
finder_kwargs={"by": By.NAME, "value": name},
original_find="name",
wait_time=wait_time,
)
def find_by_tag(self, tag, wait_time=None):
return self.find_by(
self.driver.find_elements,
finder_kwargs={"by": By.TAG_NAME, "value": tag},
original_find="tag_name",
wait_time=wait_time,
)
def find_by_value(self, value, wait_time=None):
elem = self.find_by_xpath(
f'//*[@value="{value}"]',
original_find="value",
original_query=value,
wait_time=wait_time,
)
if elem:
return elem
return self.find_by_xpath('//*[.="%s"]' % value)
def find_by_text(self, text=None, wait_time=None):
xpath_str = _concat_xpath_from_str(text)
return self.find_by_xpath(
xpath_str,
original_find="text",
original_query=text,
wait_time=wait_time,
)
def find_by_id(self, id, wait_time=None): # NOQA: A002
return self.find_by(
self.driver.find_element,
finder_kwargs={"by": By.ID, "value": id},
original_find="id",
wait_time=wait_time,
)
def fill(self, name, value):
field = self.find_by_name(name).first
field.value = value
attach_file = fill
def fill_form(self, field_values, form_id=None, name=None, ignore_missing=False):
form = None
if name is not None:
form = self.find_by_name(name)
if form_id is not None:
form = self.find_by_id(form_id)
for name, value in field_values.items():
try:
if form:
elements = form.find_by_name(name)
else:
elements = self.find_by_name(name)
element = elements.first
if element["type"] in ["text", "password", "tel"] or element.tag_name == "textarea":
element.value = value
elif element["type"] == "checkbox":
if value:
element.check()
else:
element.uncheck()
elif element["type"] == "radio":
for field in elements:
if field.value == value:
field.click()
elif element._element.tag_name == "select":
element.select(value)
else:
element.value = value
except ElementDoesNotExist as e:
if not ignore_missing:
raise ElementDoesNotExist(e)
def type(self, name, value, slowly=False): # NOQA: A003
element = self.find_by_name(name).first._element
if slowly:
return TypeIterator(element, value)
element.send_keys(value)
return value
def choose(self, name, value):
fields = self.find_by_name(name)
for field in fields:
if field.value == value:
field.click()
def check(self, name):
self.find_by_name(name).first.check()
def uncheck(self, name):
self.find_by_name(name).first.uncheck()
def screenshot(self, name="", suffix=".png", full=False, unique_file=True):
filename = f"{name}{suffix}"
if unique_file:
(fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
# Don't hold the file
os.close(fd)
if full:
ori_window_size = self.driver.get_window_size()
self.full_screen()
self.driver.get_screenshot_as_file(filename)
if full:
self.recover_screen(ori_window_size)
return filename
def html_snapshot(
self,
name="",
suffix=".html",
encoding="utf-8",
unique_file=True,
):
filename = f"{name}{suffix}"
if unique_file:
(fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
# Don't hold the file
os.close(fd)
with open(filename, "w", encoding=encoding) as f:
f.write(self.html)
return filename
def select(self, name, value):
self.find_by_xpath(
f'//select[@name="{name}"]//option[@value="{value}"]',
).first._element.click()
def select_by_text(self, name, text):
self.find_by_xpath(
f'//select[@name="{name}"]/option[text()="{text}"]',
).first._element.click()
def quit(self): # NOQA: A003
try:
self.driver.quit()
except WebDriverException:
pass
def full_screen(self):
width = self.driver.execute_script(
"return Math.max(document.body.scrollWidth, document.body.offsetWidth);",
)
height = self.driver.execute_script(
"return Math.max(document.body.scrollHeight, document.body.offsetHeight);",
)
self.driver.set_window_size(width, height)
def recover_screen(self, size):
width = size.get("width")
height = size.get("height")
self.driver.set_window_size(width, height)
@property
def cookies(self):
return self._cookie_manager
@property
def windows(self):
return Windows(self)
class TypeIterator:
def __init__(self, element, keys):
self._element = element
self._keys = keys
def __iter__(self):
for key in self._keys:
self._element.send_keys(key)
yield key
class ShadowRootElement(ElementAPI):
find_by = find_by
def __init__(self, element, parent):
self._element = element
self.parent = parent
self.driver = self.parent.driver
self.wait_time = self.parent.wait_time
self.element_class = self.parent.element_class
def _find(self, by: By, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": by, "value": selector},
wait_time=wait_time,
)
def find_by_css(self, selector, wait_time=None):
return self._find(By.CSS_SELECTOR, selector, wait_time)
def find_by_id(self, selector, wait_time=None):
return self._find(By.ID, selector, wait_time)
def find_by_name(self, selector, wait_time=None):
return self._find(By.NAME, selector, wait_time)
def find_by_tag(self, selector, wait_time=None):
return self._find(By.TAG_NAME, selector, wait_time)
class WebDriverElement(ElementAPI):
find_by = find_by
def __init__(self, element, parent, finder_kwargs):
self._element = element
self.parent = parent
self._find_elements = self._element.find_elements
self._finder_kwargs = finder_kwargs
self.driver = self.parent.driver
self.wait_time = self.parent.wait_time
self.element_class = self.parent.element_class
self.links = FindLinks(self)
def _get_value(self):
return self["value"] or self._element.text
def _set_value(self, value):
if self._element.get_attribute("type") != "file":
self._element.clear()
self._element.send_keys(value)
value = property(_get_value, _set_value)
def __getitem__(self, attr):
return self._element.get_attribute(attr)
@property
def text(self):
return self._element.text
@property
def tag_name(self):
return self._element.tag_name
def clear(self):
if self._element.get_attribute("type") in [
"email",
"number",
"password",
"search",
"tel",
"text",
"textarea",
"url",
]:
self._element.clear()
def fill(self, value):
self.value = value
def select(self, value=None, text=None):
finder = None
search_value = None
if text:
finder = "text()"
search_value = text
elif value:
finder = "@value"
search_value = value
self.find_by_xpath(
f'.//option[{finder}="{search_value}"]',
)._element.click()
def select_by_text(self, text):
self.select(text=text)
def type(self, value, slowly=False): # NOQA: A003
if slowly:
return TypeIterator(self._element, value)
self._element.send_keys(value)
return value
def click(self):
"""Click an element.
If the element is not interactive due to being covered by another
element, the click will retry for self.parent.wait_time amount of
time.
"""
end_time = time.time() + self.parent.wait_time
error = None
while time.time() < end_time:
try:
return self._element.click()
except (
ElementClickInterceptedException,
WebDriverException,
) as e:
error = e
raise error
def check(self):
if not self.checked:
self.click()
def uncheck(self):
if self.checked:
self.click()
@property
def checked(self):
return self._element.is_selected()
selected = checked
@property
def visible(self):
return self._element.is_displayed()
@property
def html(self):
return self["innerHTML"]
@property
def outer_html(self):
return self["outerHTML"]
def _refresh_element(self, wait_time: Optional[int] = None):
"""Search for the element and update the internal reference.
Returns:
WebDriverElement
Raises:
ElementDoesNotExist
"""
element_list = self.find_by(
self.parent._find_elements,
finder_kwargs=self._finder_kwargs,
original_find=self._finder_kwargs["by"],
wait_time=wait_time,
)
# Ensure the correct element is picked and replace old element
for elem in element_list:
new_element = elem._element
if new_element == self._element:
self._element = new_element
return self
raise ElementDoesNotExist("Element was removed from DOM.")
def is_visible(self, wait_time=None):
wait_time = wait_time or self.wait_time
def search() -> bool:
# Element is refreshed to account for changes to the page.
self._refresh_element(wait_time=0)
try:
result = self.visible
# StaleElementReferenceException occurs if element is found
# but changes before visible is checked
except StaleElementReferenceException:
return False
if result:
return True
return False
return _retry(search, timeout=wait_time)
def is_not_visible(self, wait_time=None):
wait_time = wait_time or self.wait_time
def search() -> bool:
# Element is refreshed to account for changes to the page.
self._refresh_element(wait_time=0)
try:
result = self.visible
# StaleElementReferenceException occurs if element is found
# but changes before visible is checked
except StaleElementReferenceException:
return False
if result:
return False
return True
return _retry(search, timeout=wait_time)
def find_by_css(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.CSS_SELECTOR, "value": selector},
original_find="css",
wait_time=wait_time,
)
def find_by_xpath(
self,
selector,
wait_time=None,
original_find="xpath",
original_query=None,
):
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.XPATH, "value": selector},
original_find=original_find,
original_query=original_query,
wait_time=wait_time,
)
def find_by_name(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.NAME, "value": selector},
original_find="name",
wait_time=wait_time,
)
def find_by_tag(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.TAG_NAME, "value": selector},
original_find="tag",
wait_time=wait_time,
)
def find_by_value(self, value, wait_time=None):
selector = f'[value="{value}"]'
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.CSS_SELECTOR, "value": selector},
original_find="value",
original_query=value,
wait_time=wait_time,
)
def find_by_text(self, text, wait_time=None):
# Add a period to the xpath to search only inside the parent.
xpath_str = f".{_concat_xpath_from_str(text)}"
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.XPATH, "value": xpath_str},
original_find="text",
original_query=text,
wait_time=wait_time,
)
def find_by_id(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
finder_kwargs={"by": By.ID, "value": selector},
original_find="id",
wait_time=wait_time,
)
def has_class(self, class_name):
return bool(
re.search(r"(?:^|\s)" + re.escape(class_name) + r"(?:$|\s)", self["class"]),
)
def scroll_to(self):
"""Scroll to the current element."""
self.driver.execute_script("arguments[0].scrollIntoView(true);", self._element)
def mouse_over(self):
"""Perform a mouse over the element."""
self.scroll_to()
ActionChains(self.driver).move_to_element(self._element).perform()
def mouse_out(self):
"""Perform a mouse out the element."""
self.scroll_to()
size = self._element.size
try:
# Fails on left edge of viewport
ActionChains(self.driver).move_to_element_with_offset(
self._element,
-10,
-10,
).click().perform()
except MoveTargetOutOfBoundsException:
try:
ActionChains(self.driver).move_to_element_with_offset(
self._element,
size["width"] + 10,
10,