-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathbot.py
More file actions
2263 lines (1870 loc) · 76.4 KB
/
bot.py
File metadata and controls
2263 lines (1870 loc) · 76.4 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
from __future__ import annotations
import atexit
import base64
import functools
import glob
import io
import json
import logging
import os
import pathlib
import platform
import random
import re
import shutil
import time
from typing import List
from contextlib import contextmanager
from botcity.base import BaseBot, State
from botcity.base.utils import only_if_element
from bs4 import BeautifulSoup
from PIL import Image
from selenium.common.exceptions import InvalidSessionIdException, WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait, TimeoutException, NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.print_page_options import PrintOptions
from weakref import ref
from . import config, cv2find, compat
from .browsers import BROWSER_CONFIGS, Browser, PageLoadStrategy
try:
from botcity.maestro import BotMaestroSDK
MAESTRO_AVAILABLE = True
except ImportError:
MAESTRO_AVAILABLE = False
logger = logging.getLogger(__name__)
def _cleanup(driver, temp_dir):
if driver() is not None:
try:
if driver().service.is_connectable():
driver().quit()
except Exception:
pass
if temp_dir:
try:
shutil.rmtree(temp_dir, ignore_errors=True)
except Exception:
pass
class WebBot(BaseBot):
KEYS = Keys
DEFAULT_DIMENSIONS = (1600, 900)
"""
Base class for Web Bots.
Users must implement the `action` method in their classes.
Attributes:
state (State): The internal state of this bot.
maestro (BotMaestroSDK): an instance to interact with the BotMaestro server.
"""
def __init__(self, headless=False):
self.state = State()
self.maestro = BotMaestroSDK() if MAESTRO_AVAILABLE else None
self._browser = Browser.CHROME
self._options = None
self._capabilities = None
self._driver_path = None
self._driver = None
self._headless = headless
self._page_load_strategy = PageLoadStrategy.NORMAL
self._binary_path = None
self._clipboard = ""
# Stub mouse coordinates
self._html_elem = None
self._x = 0
self._y = 0
# State for Key modifiers
self._shift_hold = False
self._download_folder_path = os.getcwd()
self._botcity_temp_dir = None
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
self.stop_browser()
@property
def driver(self):
"""
The WebDriver driver instance.
Returns:
driver (WebDriver): The WebDriver driver instance.
"""
return self._driver
@property
def driver_path(self):
return self._driver_path
@driver_path.setter
def driver_path(self, driver_path):
"""
The webdriver executable path.
Args:
driver_path (str): The full path to the proper webdriver path used for the selected browser.
If set to None, the code will look into the PATH for the proper file when starting the browser.
"""
driver_path = os.path.abspath(os.path.expanduser(os.path.expandvars(driver_path)))
if driver_path and not os.path.isfile(driver_path):
raise ValueError("Invalid driver_path. The file does not exist.")
self._driver_path = driver_path
@property
def browser(self):
"""
The web browser to be used.
Returns:
browser (Browser): The web browser to be used.
"""
return self._browser
@browser.setter
def browser(self, browser):
"""
The web browser to be used.
Args:
browser (Browser): The name of web browser to be used from the Browser enum.
"""
self._browser = browser
@property
def options(self):
"""
The options to be passed down to the WebDriver when starting the browser.
Returns:
options (Options): The browser specific options to be used.
"""
return self._options
@options.setter
def options(self, options):
"""
The options to be passed down to the WebDriver when starting the browser.
Args:
options (Options): The browser specific options to be used.
"""
self._options = options
@property
def capabilities(self):
"""
The capabilities to be passed down to the WebDriver when starting the browser.
Returns:
capabilities (Dict): The browser specific capabilities to be used.
"""
return self._capabilities
@capabilities.setter
def capabilities(self, capabilities):
"""
The capabilities to be passed down to the WebDriver when starting the browser.
Args:
capabilities (Dict): The browser specific capabilities to be used.
"""
self._capabilities = capabilities
@property
def download_folder_path(self):
return self._download_folder_path
@download_folder_path.setter
def download_folder_path(self, folder_path):
"""
The download folder path to be used. Set it up before starting the Browser or browsing a URL or restart the
browser after changing it.
Args:
folder_path (str): The desired download folder path.
"""
self._download_folder_path = folder_path
@property
def headless(self):
"""
Controls whether or not the bot will run headless.
Returns:
headless (bool): Whether or not to run the browser on headless mode.
"""
return self._headless
@headless.setter
def headless(self, headless):
"""
Controls whether or not the bot will run headless.
Args:
headless (boolean): If set to True will make the bot run headless.
"""
if self._driver:
logger.warning("Browser is running. Invoke stop_browser and start browser for changes to take effect.")
self._headless = headless
@property
def page_load_strategy(self) -> PageLoadStrategy:
"""
The page load strategy to be used.
Returns:
page_load_strategy (PageLoadStrategy): The page load strategy to be used.
"""
return self._page_load_strategy
@page_load_strategy.setter
def page_load_strategy(self, page_load_strategy: PageLoadStrategy):
"""
The page load strategy to be used.
Args:
page_load_strategy (PageLoadStrategy): The page load strategy to be used.
"""
if self._driver:
logger.warning("Browser is running. Invoke stop_browser and start browser for changes to take effect.")
self._page_load_strategy = page_load_strategy
@property
def binary_path(self):
"""The binary path to be used.
Returns:
binary_path (pathlib.Path): The binary path to be used.
"""
return pathlib.Path(self._binary_path)
@binary_path.setter
def binary_path(self, binary_path: str):
"""The binary path to be used.
Args:
binary_path (str): The binary path to be used.
"""
path = pathlib.Path(binary_path)
if not path.is_file():
raise ValueError("There is no file in the binary path.")
self._binary_path = path
def start_browser(self):
"""
Starts the selected browser.
"""
def check_driver():
# Look for driver
driver_name = BROWSER_CONFIGS.get(self.browser).get("driver")
location = shutil.which(driver_name)
if not location:
raise RuntimeError(
f"{driver_name} was not found. Please make sure to have it on your PATH or set driver_path")
return location
# Specific webdriver class for a given browser
driver_class = BROWSER_CONFIGS.get(self.browser).get("class")
# Specific default options method for a given browser
func_def_options = BROWSER_CONFIGS.get(self.browser).get("options")
# Specific capabilities method for a given browser
func_def_capabilities = BROWSER_CONFIGS.get(self.browser).get("capabilities")
opt = self.options or func_def_options(
self.headless, self._download_folder_path, None, self.page_load_strategy, self._binary_path
)
cap = self.capabilities or func_def_capabilities()
self.options = opt
self.capabilities = cap
driver_path = self.driver_path or check_driver()
self.driver_path = driver_path
self._driver = self._instantiate_driver(driver_class=driver_class, func_def_options=func_def_options)
self._others_configurations()
self.set_screen_resolution()
atexit.register(_cleanup, ref(self._driver), self.options._botcity_temp_dir)
def _instantiate_driver(self, driver_class, func_def_options):
"""
It is necessary to create this function because we isolated the instantiation of the driver,
giving options to solve some bugs, mainly in undetected chrome.
"""
try:
driver = driver_class(**self._get_parameters_to_driver())
except WebDriverException as error:
# TODO: 'Undetected Chrome' fix error to upgrade version chrome.
if 'This version of ChromeDriver only supports Chrome version' in error.msg:
self.stop_browser()
try:
correct_version = int(error.msg.split('Current browser version is ')[1].split('.')[0])
except Exception:
raise error
self.options = func_def_options(self.headless, self._download_folder_path, None,
self.page_load_strategy)
driver = driver_class(**self._get_parameters_to_driver(), version_main=correct_version)
else:
raise error
return driver
def _get_parameters_to_driver(self):
if self.browser == Browser.UNDETECTED_CHROME:
return {"options": self.options,
"desired_capabilities": self.capabilities}
if compat.version_selenium_is_larger_than_four():
return {"options": self.options, "service": self._get_service()}
return {"options": self.options, "desired_capabilities": self.capabilities,
"executable_path": self.driver_path}
def _get_service(self):
service = BROWSER_CONFIGS.get(self.browser).get("service")
service = service(executable_path=self.driver_path)
service.desired_capabilities = self.capabilities
return service
def _others_configurations(self):
if self.browser in [Browser.UNDETECTED_CHROME, Browser.CHROME, Browser.EDGE]:
"""
There is a problem in undetected chrome that prevents downloading files even passing
download_folder_path in preferences.
This solution is taken from the following issue
https://github.com/ultrafunkamsterdam/undetected-chromedriver/issues/260#issuecomment-901276808.
It will be a temporary solution.
"""
if self.browser == Browser.UNDETECTED_CHROME:
try:
self.driver.get("about:blank")
except Exception:
pass
params = {
"behavior": "allow",
"downloadPath": self.download_folder_path
}
self.driver.execute_cdp_cmd("Page.setDownloadBehavior", params)
def stop_browser(self):
"""
Stops the Chrome browser and clean up the User Data Directory.
Warning:
After invoking this method, you will need to reassign your custom options and capabilities.
"""
if not self._driver:
return
if self.get_tabs():
self.activate_tab(self.get_tabs()[-1])
self._driver.close()
self._driver.quit()
if self.options is not None:
try:
self._botcity_temp_dir = self.options._botcity_temp_dir
except Exception:
self._botcity_temp_dir = None
self.options = None
self.capabilities = None
self._driver = None
def set_screen_resolution(self, width=None, height=None):
"""
Configures the browser dimensions.
Args:
width (int): The desired width.
height (int): The desired height.
"""
dimensions = (width or self.DEFAULT_DIMENSIONS[0], height or self.DEFAULT_DIMENSIONS[1])
if self.headless:
# When running headless the window size is the viewport size
window_size = dimensions
else:
# When running non-headless we need to account for the borders and etc
# So the size must be bigger to have the same viewport size as before
window_size = self._driver.execute_script("""
return [window.outerWidth - window.innerWidth + arguments[0],
window.outerHeight - window.innerHeight + arguments[1]];
""", *dimensions)
self._driver.set_window_size(*window_size)
def _webdriver_command(self, command, params=None, req_type="POST"):
"""
Execute a webdriver command.
Args:
command (str): The command URL after the session part
params (dict): The payload to be serialized and sent to the webdriver. Defaults to None.
req_type (str, optional): The type of request to be made. Defaults to "POST".
Returns:
str: The value of the response
"""
if not params:
params = {}
resource = f"/session/{self.driver.session_id}/{command}"
url = self.driver.command_executor._url + resource
body = json.dumps(params)
response = self.driver.command_executor._request(req_type, url, body)
if not response:
raise Exception(response.get('value'))
return response.get('value')
##########
# Display
##########
def get_screen_image(self, region=None):
"""
Capture and returns a screenshot from the browser.
Args:
region (tuple): A tuple containing the left, top, width and height
to crop the screen image.
Returns:
image (Image): The screenshot Image object.
"""
if not region:
region = (0, 0, 0, 0)
x = region[0]
y = region[1]
width = region[2] or self._get_page_size()[0]
height = region[3] or self._get_page_size()[1]
try:
data = self._driver.get_screenshot_as_base64()
image_data = base64.b64decode(data)
img = Image.open(io.BytesIO(image_data))
except: # noqa: E722
img = Image.new("RGB", (width, height))
img = img.crop((x, y, x + width, y + height))
return img
def get_viewport_size(self):
"""
Returns the browser current viewport size.
Returns:
width (int): The current viewport width.
height (int): The current viewport height.
"""
# Access each dimension individually
width = self._driver.get_window_size().get("width")
height = self._driver.get_window_size().get("height")
return width, height
def _get_page_size(self):
"""
Returns the browser current page size.
Returns:
width (int): The current page width.
height (int): The current page height.
"""
if not self._driver:
return self.DEFAULT_DIMENSIONS
scale_factor = self.execute_javascript("return window.devicePixelRatio")
width = int(self.execute_javascript("return window.innerWidth") * scale_factor)
height = int(self.execute_javascript("return window.innerHeight") * scale_factor)
return width, height
def add_image(self, label, path):
"""
Add an image into the state image map.
Args:
label (str): The image identifier
path (str): The path for the image on disk
"""
self.state.map_images[label] = path
def get_image_from_map(self, label):
"""
Return an image from teh state image map.
Args:
label (str): The image identifier
Returns:
Image: The Image object
"""
path = self.state.map_images.get(label)
if not path:
raise KeyError('Invalid label for image map.')
img = Image.open(path)
return img
def find_multiple(self, labels, x=None, y=None, width=None, height=None, *,
threshold=None, matching=0.9, waiting_time=10000, best=True, grayscale=False):
"""
Find multiple elements defined by label on screen until a timeout happens.
Args:
labels (list): A list of image identifiers
x (int, optional): Search region start position x. Defaults to 0.
y (int, optional): Search region start position y. Defaults to 0.
width (int, optional): Search region width. Defaults to screen width.
height (int, optional): Search region height. Defaults to screen height.
threshold (int, optional): The threshold to be applied when doing grayscale search.
Defaults to None.
matching (float, optional): The matching index ranging from 0 to 1.
Defaults to 0.9.
waiting_time (int, optional): Maximum wait time (ms) to search for a hit.
Defaults to 10000ms (10s).
best (bool, optional): Whether or not to keep looking until the best matching is found.
Defaults to True.
grayscale (bool, optional): Whether or not to convert to grayscale before searching.
Defaults to False.
Returns:
results (dict): A dictionary in which the key is the label and value are the element coordinates in a
NamedTuple.
"""
def _to_dict(lbs, elems):
return {k: v for k, v in zip(lbs, elems)}
screen_w, screen_h = self._get_page_size()
x = x or 0
y = y or 0
w = width or screen_w
h = height or screen_h
region = (x, y, w, h)
results = [None] * len(labels)
paths = [self._search_image_file(la) for la in labels]
paths = [self._image_path_as_image(la) for la in paths]
if threshold:
# TODO: Figure out how we should do threshold
print('Threshold not yet supported')
if not best:
# TODO: Implement best=False.
print('Warning: Ignoring best=False for now. It will be supported in the future.')
start_time = time.time()
while True:
elapsed_time = (time.time() - start_time) * 1000
if elapsed_time > waiting_time:
return _to_dict(labels, results)
haystack = self.screenshot()
helper = functools.partial(self._find_multiple_helper, haystack, region, matching, grayscale)
results = [helper(p) for p in paths]
results = [r for r in results]
if None in results:
continue
else:
return _to_dict(labels, results)
def _find_multiple_helper(self, haystack, region, confidence, grayscale, needle):
ele = cv2find.locate_all_opencv(
needle, haystack, region=region, confidence=confidence, grayscale=grayscale
)
try:
ele = next(ele)
except StopIteration:
ele = None
return ele
def find(self, label, x=None, y=None, width=None, height=None, *,
threshold=None, matching=0.9, waiting_time=10000, best=True, grayscale=False):
"""
Find an element defined by label on screen until a timeout happens.
Args:
label (str): The image identifier
x (int, optional): Search region start position x. Defaults to 0.
y (int, optional): Search region start position y. Defaults to 0.
width (int, optional): Search region width. Defaults to screen width.
height (int, optional): Search region height. Defaults to screen height.
threshold (int, optional): The threshold to be applied when doing grayscale search.
Defaults to None.
matching (float, optional): The matching index ranging from 0 to 1.
Defaults to 0.9.
waiting_time (int, optional): Maximum wait time (ms) to search for a hit.
Defaults to 10000ms (10s).
best (bool, optional): Whether or not to keep looking until the best matching is found.
Defaults to True.
grayscale (bool, optional): Whether or not to convert to grayscale before searching.
Defaults to False.
Returns:
element (NamedTuple): The element coordinates. None if not found.
"""
return self.find_until(label=label, x=x, y=y, width=width, height=height, threshold=threshold,
matching=matching, waiting_time=waiting_time, best=best, grayscale=grayscale)
def find_until(self, label, x=None, y=None, width=None, height=None, *,
threshold=None, matching=0.9, waiting_time=10000, best=True, grayscale=False):
"""
Find an element defined by label on screen until a timeout happens.
Args:
label (str): The image identifier
x (int, optional): Search region start position x. Defaults to 0.
y (int, optional): Search region start position y. Defaults to 0.
width (int, optional): Search region width. Defaults to screen width.
height (int, optional): Search region height. Defaults to screen height.
threshold (int, optional): The threshold to be applied when doing grayscale search.
Defaults to None.
matching (float, optional): The matching index ranging from 0 to 1.
Defaults to 0.9.
waiting_time (int, optional): Maximum wait time (ms) to search for a hit.
Defaults to 10000ms (10s).
best (bool, optional): Whether or not to keep looking until the best matching is found.
Defaults to True.
grayscale (bool, optional): Whether or not to convert to grayscale before searching.
Defaults to False.
Returns:
element (NamedTuple): The element coordinates. None if not found.
"""
self.state.element = None
screen_w, screen_h = self._get_page_size()
x = x or 0
y = y or 0
w = width or screen_w
h = height or screen_h
region = (x, y, w, h)
element_path = self._search_image_file(label)
element_path = self._image_path_as_image(element_path)
if threshold:
# TODO: Figure out how we should do threshold
print('Threshold not yet supported')
if not best:
# TODO: Implement best=False.
print('Warning: Ignoring best=False for now. It will be supported in the future.')
start_time = time.time()
while True:
elapsed_time = (time.time() - start_time) * 1000
if elapsed_time > waiting_time:
return None
haystack = self.get_screen_image()
it = cv2find.locate_all_opencv(element_path, haystack_image=haystack,
region=region, confidence=matching, grayscale=grayscale)
try:
ele = next(it)
except StopIteration:
ele = None
if ele is not None:
self.state.element = ele
return ele
def set_current_element(self, element: cv2find.Box):
"""
Changes the current screen element the bot will interact when using click(), move(), and similar methods.
This method is equivalent to self.state.element = element.
Args:
element (Box): A screen element from self.state.element or the find_all(as_list=True) method.
"""
self.state.element = element
def find_all(self, label, x=None, y=None, width=None, height=None, *,
threshold=None, matching=0.9, waiting_time=10000, grayscale=False, as_list: bool = False):
"""
Find all elements defined by label on screen until a timeout happens.
Args:
label (str): The image identifier
x (int, optional): Search region start position x. Defaults to 0.
y (int, optional): Search region start position y. Defaults to 0.
width (int, optional): Search region width. Defaults to screen width.
height (int, optional): Search region height. Defaults to screen height.
threshold (int, optional): The threshold to be applied when doing grayscale search.
Defaults to None.
matching (float, optional): The matching index ranging from 0 to 1.
Defaults to 0.9.
waiting_time (int, optional): Maximum wait time (ms) to search for a hit.
Defaults to 10000ms (10s).
grayscale (bool, optional): Whether or not to convert to grayscale before searching.
Defaults to False.
as_list (bool, Optional): If True, returns a list of element coordinates instead of a generator.
Use set_active_element() to be able to interact with the found elements.
This parameter must be True if you intend to run multiple find_all() concurrently.
Defaults to False.
Returns:
elements (collections.Iterable[NamedTuple]): A generator with all element coordinates found.
None if not found.
"""
def deduplicate(elems):
def find_same(item, items):
x_start = item.left
x_end = item.left + item.width
y_start = item.top
y_end = item.top + item.height
similars = []
for itm in items:
if itm == item:
continue
if (itm.left >= x_start and itm.left < x_end)\
and (itm.top >= y_start and itm.top < y_end):
similars.append(itm)
continue
return similars
index = 0
while True:
try:
dups = find_same(elems[index], elems[index:])
for d in dups:
elems.remove(d)
index += 1
except IndexError:
break
return elems
self.state.element = None
screen_w, screen_h = self._get_page_size()
x = x or 0
y = y or 0
w = width or screen_w
h = height or screen_h
region = (x, y, w, h)
element_path = self._search_image_file(label)
element_path = self._image_path_as_image(element_path)
if threshold:
# TODO: Figure out how we should do threshold
print('Threshold not yet supported')
start_time = time.time()
while True:
elapsed_time = (time.time() - start_time) * 1000
if elapsed_time > waiting_time:
return None
haystack = self.get_screen_image()
it = cv2find.locate_all_opencv(element_path, haystack_image=haystack,
region=region, confidence=matching, grayscale=grayscale)
eles = [ele for ele in it]
if not eles:
continue
eles = deduplicate(list(eles))
# As List
if as_list:
return eles
# As Generator
for ele in eles:
if ele is not None:
self.state.element = ele
yield ele
break
def find_text(self, label, x=None, y=None, width=None, height=None, *, threshold=None, matching=0.9,
waiting_time=10000, best=True):
"""
Find an element defined by label on screen until a timeout happens.
Args:
label (str): The image identifier
x (int, optional): Search region start position x. Defaults to 0.
y (int, optional): Search region start position y. Defaults to 0.
width (int, optional): Search region width. Defaults to screen width.
height (int, optional): Search region height. Defaults to screen height.
threshold (int, optional): The threshold to be applied when doing grayscale search.
Defaults to None.
matching (float, optional): The matching index ranging from 0 to 1.
Defaults to 0.9.
waiting_time (int, optional): Maximum wait time (ms) to search for a hit.
Defaults to 10000ms (10s).
best (bool, optional): Whether or not to keep looking until the best matching is found.
Defaults to True.
Returns:
element (NamedTuple): The element coordinates. None if not found.
"""
return self.find_until(label, x, y, width, height, threshold=threshold, matching=matching,
waiting_time=waiting_time, best=best, grayscale=True)
def get_last_element(self):
"""
Return the last element found.
Returns:
element (NamedTuple): The element coordinates (left, top, width, height)
"""
return self.state.element
def display_size(self):
"""
Returns the display size in pixels.
Returns:
size (Tuple): The screen dimension (width and height) in pixels.
"""
return self._get_page_size()
def screenshot(self, filepath=None, region=None):
"""
Capture a screenshot.
Args:
filepath (str, optional): The filepath in which to save the screenshot. Defaults to None.
region (tuple, optional): Bounding box containing left, top, width and height to crop screenshot.
Returns:
Image: The screenshot Image object
"""
img = self.get_screen_image(region)
if filepath:
img.save(filepath)
return img
def get_screenshot(self, filepath=None, region=None):
"""
Capture a screenshot.
Args:
filepath (str, optional): The filepath in which to save the screenshot. Defaults to None.
region (tuple, optional): Bounding box containing left, top, width and height to crop screenshot.
Returns:
Image: The screenshot Image object
"""
return self.screenshot(filepath, region)
def screen_cut(self, x, y, width=None, height=None):
"""
Capture a screenshot from a region of the screen.
Args:
x (int): region start position x
y (int): region start position y
width (int): region width
height (int): region height
Returns:
Image: The screenshot Image object
"""
screen_size = self._get_page_size()
x = x or 0
y = y or 0
width = width or screen_size[0]
height = height or screen_size[1]
img = self.screenshot(region=(x, y, width, height))
return img
def save_screenshot(self, path):
"""
Saves a screenshot in a given path.
Args:
path (str): The filepath in which to save the screenshot
"""
self.screenshot(path)
def get_element_coords(self, label, x=None, y=None, width=None, height=None, matching=0.9, best=True):
"""
Find an element defined by label on screen and returns its coordinates.
Args:
label (str): The image identifier
x (int, optional): X (Left) coordinate of the search area.
y (int, optional): Y (Top) coordinate of the search area.
width (int, optional): Width of the search area.
height (int, optional): Height of the search area.
matching (float, optional): Minimum score to consider a match in the element image recognition process.
Defaults to 0.9.
best (bool, optional): Whether or not to search for the best value. If False the method returns on
the first find. Defaults to True.
Returns:
coords (Tuple): A tuple containing the x and y coordinates for the element.
"""
self.state.element = None
screen_size = self._get_page_size()
x = x or 0
y = y or 0
width = width or screen_size[0]
height = height or screen_size[1]
region = (x, y, width, height)
if not best:
print('Warning: Ignoring best=False for now. It will be supported in the future.')
element_path = self._search_image_file(label)
element_path = self._image_path_as_image(element_path)
haystack = self.get_screen_image()
it = cv2find.locate_all_opencv(element_path, haystack_image=haystack,
region=region, confidence=matching)
try:
ele = next(it)
except StopIteration:
ele = None
self.state.element = ele
if ele:
return ele.left, ele.top
else:
return None, None
def get_element_coords_centered(self, label, x=None, y=None, width=None, height=None,
matching=0.9, best=True):
"""
Find an element defined by label on screen and returns its centered coordinates.
Args:
label (str): The image identifier
x (int, optional): X (Left) coordinate of the search area.
y (int, optional): Y (Top) coordinate of the search area.
width (int, optional): Width of the search area.
height (int, optional): Height of the search area.
matching (float, optional): Minimum score to consider a match in the element image recognition process.
Defaults to 0.9.
best (bool, optional): Whether or not to search for the best value. If False the method returns on
the first find. Defaults to True.
Returns:
coords (Tuple): A tuple containing the x and y coordinates for the center of the element.
"""
self.get_element_coords(label, x, y, width, height, matching, best)
return self.state.center()
#########
# Browser
#########
def page_title(self):
"""
Returns the active page title.
Returns:
title (str): The page title.
"""
try:
return self._driver.title
except InvalidSessionIdException:
return None
def page_source(self):
"""
Returns the active page source.
Returns:
soup (BeautifulSoup): BeautifulSoup object for the page source.
"""