-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathwebdriver.py
More file actions
1533 lines (1273 loc) · 63.4 KB
/
Copy pathwebdriver.py
File metadata and controls
1533 lines (1273 loc) · 63.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
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# modified by kaliiiiiiiiii | Aurin Aegerter
# all modifications are licensed under the license provided at LICENSE.md
"""The WebDriver implementation."""
import os
import shutil
import subprocess
import sys
import tempfile
import time
import typing
import uuid
import warnings
import signal
from typing import List
# io
import asyncio
import cdp_socket.exceptions
import websockets
# interactions
from selenium_driverless.input.pointer import Pointer
from selenium_driverless.types.webelement import WebElement
from selenium_driverless.scripts.switch_to import SwitchTo
# contexts
from selenium_driverless.sync.context import Context as SyncContext
from selenium_driverless.types.context import Context
# Targets
from selenium_driverless.scripts.driver_utils import get_target
from selenium_driverless.types.target import Target, TargetInfo
from selenium_driverless.types.base_target import BaseTarget
from selenium_driverless.sync.base_target import BaseTarget as SyncBaseTarget
# others
from cdp_socket.utils.conn import get_json
from selenium_driverless.types.options import Options as ChromeOptions
from selenium_driverless.utils.utils import sel_driverless_path
from selenium_driverless.types import JSEvalException
from selenium_driverless import EXC_HANDLER
class Chrome:
"""Control the chromium based browsers without any driver."""
port: int
def __init__(
self,
options: ChromeOptions = None,
timeout: float = 30,
debug: bool = False,
max_ws_size: int = 2 ** 27
) -> None:
# noinspection GrazieInspection
"""Creates a new instance of the chrome target. Starts the service and
then creates new instance of chrome target.
.. code-block:: python
options = webdriver.ChromeOptions.rst()
async with webdriver.Chrome(options=options) as driver:
await driver.get('https://abrahamjuliot.github.io/creepjs/', wait_load=True)
print(await driver.title)
:param options: this takes an instance of ChromeOptions.rst
:param timeout: timeout in seconds to start chrome
:param debug: redirect errors from the chromium process output (stderr) to console
:param max_ws_size: maximum size for websocket messages in bytes. 2^27 ~= 130 MB by default
"""
self._prefs = {}
self._auth_interception_enabled = None
self._mv3_extension = None
self._extensions_incognito_allowed = None
self._base_context = None
self._stderr = None
self._stderr_file = None
self._process = None
self._current_target = None
self._host = None
self._timeout = timeout
self._loop: asyncio.AbstractEventLoop or None = None
self.browser_pid: int or None = None
self._base_target = None
self._debug = debug
# noinspection PyTypeChecker
self._current_context: Context = None
self._contexts: typing.Dict[str, Context] = {}
self._temp_dir = tempfile.TemporaryDirectory(prefix="selenium_driverless_").name
self._max_ws_size = max_ws_size
self._auth = {}
if not options:
options = ChromeOptions()
if not options.binary_location:
from selenium_driverless.utils.utils import find_chrome_executable
options.binary_location = find_chrome_executable()
self._options: ChromeOptions = options
self._is_remote = True
self._is_remote = False
self._has_incognito_contexts: bool = False
self._started = False
def __repr__(self):
return f'<{type(self).__module__}.{type(self).__name__} (session="{self.current_target.id}")>'
async def __aenter__(self):
await self.start_session()
return self
def __enter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.quit(clean_dirs=self._options.auto_clean_dirs)
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __await__(self):
return self.start_session().__await__()
async def start_session(self):
if not self._started:
from selenium_driverless.utils.utils import read
from selenium_driverless.utils.utils import is_first_run, get_default_ua, set_default_ua
from selenium_driverless.scripts.prefs import read_prefs, write_prefs
await is_first_run()
user_agent = await get_default_ua()
if self._options.use_extension:
# extension
self._options.add_extension(sel_driverless_path() + "files/mv3_extension")
if not self._options.debugger_address:
from selenium_driverless.utils.utils import random_port
port = random_port()
self._options._debugger_address = f"127.0.0.1:{port}"
self._options.add_argument(f"--remote-debugging-port={port}")
if self._options.headless and not self._is_remote:
# patch useragent
if user_agent:
self._options.add_argument(f"--user-agent={user_agent}")
else:
warnings.warn("headless is detectable at first run")
# handle prefs
if self._options.user_data_dir:
prefs_path = self._options.user_data_dir + "/Default/Preferences"
if os.path.isfile(prefs_path):
self._prefs = await read_prefs(prefs_path)
else:
os.makedirs(os.path.dirname(prefs_path), exist_ok=True)
# write prefs
self._prefs.update(self._options.prefs)
await write_prefs(self._prefs, prefs_path)
elif self._options.user_data_dir is None:
self._options.add_argument(
"--user-data-dir=" + self._temp_dir + "/data_dir")
prefs_path = self._options.user_data_dir + "/Default/Preferences"
os.makedirs(os.path.dirname(prefs_path), exist_ok=True)
# write prefs
self._prefs.update(self._options.prefs)
await write_prefs(self._prefs, prefs_path)
# noinspection PyProtectedMember
# handle extensions
if self._options._extension_paths:
import zipfile
extension_paths = []
loop = asyncio.get_running_loop()
# noinspection PyProtectedMember
def extractall():
for _path in self._options._extension_paths:
if os.path.isfile(_path):
with zipfile.ZipFile(_path, 'r') as zip_ref:
_path = self._temp_dir + f"/{uuid.uuid4().hex}"
zip_ref.extractall(_path)
extension_paths.append(_path)
await loop.run_in_executor(None, extractall)
self._options.arguments.append(f"--load-extension=" + ','.join(extension_paths))
self._options._extension_paths = []
if self._options.startup_url:
self._options.add_argument(self._options.startup_url)
self._options._startup_url = None
options = self._options
# noinspection PyProtectedMember
self._is_remote = self._options._is_remote
if not self._is_remote:
path = options.binary_location
args = options.arguments
if self._debug:
self._stderr = sys.stderr
else:
self._stderr = tempfile.TemporaryFile(prefix="selenium_driverless")
self._stderr_file = self._stderr
self._process = subprocess.Popen(
[path, *args],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=self._stderr,
close_fds=True,
preexec_fn=os.setsid if os.name == 'posix' else None,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0,
shell=False,
text=True,
env=self._options.env
)
host, port = self._options.debugger_address.split(":")
port = int(port)
if port == 0:
path = self._options.user_data_dir + "/DevToolsActivePort"
while not os.path.isfile(path):
await asyncio.sleep(0.1)
port = await read(path, sel_root=False)
port = int(port.split("\n")[0])
self._options.debugger_address = f"127.0.0.1:{port}"
host, port = self._options.debugger_address.split(":")
self.port = int(port)
self._host = f"{host}:{self.port}"
if self._loop:
self._base_target = await SyncBaseTarget(host=self._host, is_remote=self._is_remote,
timeout=self._timeout, loop=self._loop,
max_ws_size=self._max_ws_size)
else:
self._base_target = await BaseTarget(host=self._host, is_remote=self._is_remote,
timeout=self._timeout, loop=self._loop,
max_ws_size=self._max_ws_size)
# fetch useragent at first headless run
# noinspection PyUnboundLocalVariable
if not self._is_remote:
res = await self._base_target.execute_cdp_cmd("Browser.getVersion")
user_agent = res["userAgent"]
user_agent = user_agent.replace("HeadlessChrome", "Chrome")
await set_default_ua(user_agent)
if not self._is_remote:
# noinspection PyUnboundLocalVariable
self.browser_pid = self._process.pid
targets = await get_json(self._host, timeout=self._timeout)
for target in targets:
if target["type"] == "page" and not target["url"].startswith("chrome-extension://"):
target_id = target["id"]
self._current_target = await get_target(target_id=target_id, host=self._host,
loop=self._loop, is_remote=self._is_remote, timeout=10,
max_ws_size=self._max_ws_size, driver=self, context=None)
# handle the context
if self._loop:
context = await SyncContext(base_target=self._current_target, driver=self, loop=self._loop,
max_ws_size=self._max_ws_size)
else:
context = await Context(base_target=self._current_target, driver=self, loop=self._loop,
max_ws_size=self._max_ws_size)
_id = context.context_id
self._current_target._context = context
def remove_context():
if _id in self._contexts:
del self._contexts[_id]
self._base_context = None
# noinspection PyProtectedMember
context._closed_callbacks.append(remove_context)
self._current_context = context
self._base_context = context
self._contexts[_id] = context
break
await self.execute_cdp_cmd("Emulation.setFocusEmulationEnabled", {"enabled": True})
if self._options.single_proxy:
await self.set_single_proxy(self._options.single_proxy)
downloads_dir = self._options.downloads_dir
if self._options.downloads_dir:
# ensure download events are dispatched
await self.set_download_behaviour("allowAndName", downloads_dir)
else:
await self.set_download_behaviour("default")
self._started = True
return self
@property
async def frame_tree(self) -> dict:
"""
**async**
all nested frames within the current target
"""
return await self.current_context.frame_tree
@property
async def targets(self) -> typing.Dict[str, TargetInfo]:
"""
**async**
all targets within the current context
"""
return await self.current_context.targets
@property
async def contexts(self) -> typing.Dict[str, Context]:
"""
**async**
all (incognito) contexts on Chrome.
"""
targets = await self.get_targets(context_id=None)
contexts = {}
for info in targets.values():
_id = info.browser_context_id
if _id:
context = self._contexts.get(_id)
if not context:
if self._loop:
context = await SyncContext(base_target=self._current_target, context_id=_id,
loop=self._loop, max_ws_size=self._max_ws_size, driver=self)
else:
context = await Context(base_target=self._current_target, context_id=_id,
loop=self._loop, max_ws_size=self._max_ws_size, driver=self)
contexts[_id] = context
self._contexts.update(contexts)
return self._contexts
async def new_context(self, proxy_bypass_list: typing.List[str] = None, proxy_server: str = True,
universal_access_origins: typing.List[str] = None, url: str = "about:blank") -> Context:
"""
creates a new (incognito) context
:param url: the url the first tab will start at. "about:blank" by default
:param universal_access_origins: An optional list of origins to grant unlimited cross-origin access to. Parts of the URL other than those constituting origin are ignored
.. warning::
The proxy parameter doesn't work on Windows due to `crbug#1310057 <https://bugs.chromium.org/p/chromium/issues/detail?id=1310057>`__.
.. code block:: python
await driver.set_auth("username", "password", "localhost:5000")
context = await driver.new_context(proxy_bypass_list=["localhost"], proxy_server="http://localhost:5000")
:param proxy_server: a proxy-server to use for the context
:param proxy_bypass_list: a list of proxies to ignore
"""
await self.ensure_extensions_incognito_allowed()
if proxy_bypass_list is None:
proxy_bypass_list = ["localhost"]
if proxy_server is None:
proxy_server = ""
args = {"disposeOnDetach": False}
if proxy_bypass_list:
args["proxyBypassList"] = ",".join(proxy_bypass_list)
if not (proxy_server is True):
args["proxyServer"] = proxy_server
if universal_access_origins:
args["originsWithUniversalNetworkAccess"] = universal_access_origins
# create context ensuring extension racing conditions
self._auth_interception_enabled = False
has_incognito_ctxs = not (not self._has_incognito_contexts)
self._has_incognito_contexts = True
mv3_ext = await self.mv3_extension
self._mv3_extension = None
try:
res = await self.base_target.execute_cdp_cmd("Target.createBrowserContext", args)
except Exception as e:
self._mv3_extension = mv3_ext
self._auth_interception_enabled = True
self._has_incognito_contexts = has_incognito_ctxs
raise e
_id = res["browserContextId"]
if self._loop:
context = await SyncContext(base_target=self._base_target, context_id=_id, loop=self._loop,
is_incognito=True,
max_ws_size=self._max_ws_size, driver=self)
else:
context = await Context(base_target=self._base_target, context_id=_id, loop=self._loop,
is_incognito=True, max_ws_size=self._max_ws_size,
driver=self)
self._contexts[_id] = context
def remove_context():
if _id in self._contexts:
del self._contexts[_id]
# noinspection PyProtectedMember
context._closed_callbacks.append(remove_context)
await context.switch_to.new_window("window", activate=False, url=url)
tabs = await context.get_targets(_type="page", context_id=_id)
context._current_target = list(tabs.values())[0].Target
context._current_target._timeout = 5
# reload auth & extension target to fix non-applied auth
if self._auth:
self._mv3_extension = None
while True:
# ensure racing conditions with extension
try:
mv3_target = await self.mv3_extension
self._auth_interception_enabled = False
await self._ensure_auth_interception(timeout=0.5, set_flag=False)
await mv3_target.execute_script("globalThis.authCreds = arguments[0]", self._auth, timeout=0.5,
unique_context=False)
except (asyncio.TimeoutError, TimeoutError):
await asyncio.sleep(0.1)
self._mv3_extension = None
else:
self._auth_interception_enabled = True
self._mv3_extension = mv3_target
return context
return context
async def get_targets(self,
_type: typing.Literal["page", "background_page", "service_worker", "browser", "other"] = None,
context_id: str or None = "self") -> typing.Dict[str, TargetInfo]:
"""
get all targets within the current context
:param _type: filter by target type
:param context_id: if ``None``, this function returns all targets for all contexts.
"""
return await self.current_context.get_targets(_type=_type, context_id=context_id)
@property
def current_target(self) -> Target:
"""
the current Target
"""
if self.current_context:
return self.current_context.current_target
return self._current_target
@property
def base_target(self) -> BaseTarget:
"""
The connection handle for the global connection to Chrome
.. warning::
only the bindings for using the CDP-protocol on BaseTarget supported
"""
return self._base_target
@property
async def mv3_extension(self, timeout: float = 10) -> Target:
"""
**async** the target for the background script of the by default loaded Chrome-extension (manifest-version==3)
.. note:
for incognito context, the extension uses the "spanning" configuration, as there isn't a way to debug "split" mode over CDP
"""
if self._has_incognito_contexts:
await self.ensure_extensions_incognito_allowed()
if not self._mv3_extension:
import re
import time
start = time.perf_counter()
extension_target = None
while not extension_target:
targets = await self.get_targets(context_id=None)
for target in targets.values():
if target.type == "service_worker":
if re.fullmatch(
r"chrome-extension://(.*)/"
r"driverless_background_mv3_243ffdd55e32a012b4f253b2879af978\.js",
target.url):
extension_target = target.Target
break
if not extension_target:
if (time.perf_counter() - start) > timeout:
raise asyncio.TimeoutError(f"Couldn't find mv3 extension within {timeout} seconds")
while True:
try:
# fix WebRTC leak
await extension_target.execute_script(
"chrome.privacy.network.webRTCIPHandlingPolicy.set(arguments[0])",
{"value": "disable_non_proxied_udp"}, timeout=2, unique_context=False)
except (asyncio.TimeoutError, TimeoutError):
await asyncio.sleep(0.2)
return await self.mv3_extension
except JSEvalException:
await asyncio.sleep(0.2)
except cdp_socket.exceptions.CDPError as e:
if e.code == -32000 and e.message == 'Could not find object with given id':
await asyncio.sleep(0.2)
else:
break
self._mv3_extension = extension_target
return self._mv3_extension
async def ensure_extensions_incognito_allowed(self):
"""
ensure that all installed Chrome-extensions are allowed in incognito context.
.. warning::
Generally, the extension decides whether to use the ``split``, ``spanning`` or ``not_allowed`` configuration.
For changing this behaviour, you'll have to modify the ``manifest.json`` file within the compressed extension or directory.
See `developer.chrome.com/docs/extensions/reference/manifest/incognito <https://developer.chrome.com/docs/extensions/reference/manifest/incognito?hl=en>`__.
"""
if not self._extensions_incognito_allowed:
self._extensions_incognito_allowed = True
# noinspection PyTypeChecker
page = None
try:
base_ctx = self._base_context
page: Context = await base_ctx.new_window("tab", "chrome://extensions", activate=False)
script = """
async function make_global(){
const extensions = await chrome.developerPrivate.getExtensionsInfo();
extensions.forEach( async function(extension) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: extension.id,
incognitoAccess: true
})
});
};
await make_global()
"""
await asyncio.sleep(0.1)
await page.eval_async(script, timeout=10, unique_context=False)
except Exception as e:
EXC_HANDLER(e)
self._extensions_incognito_allowed = False
if page:
await page.close()
await self.ensure_extensions_incognito_allowed()
self._extensions_incognito_allowed = True
await page.close()
@property
def base_context(self) -> Context:
"""
the Context which isn't incognito
"""
return self._base_context
@property
def downloads_dir(self):
"""the current downloads directory for the current context"""
return self.base_target.downloads_dir_for_context(context_id="DEFAULT")
async def set_download_behaviour(self, behaviour: typing.Literal["deny", "allow", "allowAndName", "default"],
path: str = None):
"""set the download behaviour
:param behaviour: the behaviour to set the downloading to
:param path: the path to the default download directory
.. warning::
setting ``behaviour=allow`` instead of ``allowAndName`` can cause some bugs
"""
await self.current_context.set_download_behaviour(behaviour, path)
@property
def current_context(self) -> Context:
"""
the current context switched to
"""
if not self._current_context:
if self._contexts:
return list(self._contexts.values())[0]
return self._current_context
@property
async def _isolated_context_id(self):
# noinspection PyProtectedMember
return await self.current_context._isolated_context_id
async def get_target(self, target_id: str = None, timeout: float = 2) -> Target:
"""
get a Target by TargetId for advanced usage of the CDP protocol
:param target_id:
:param timeout: timeout in seconds for connecting to the target if it's not tracked already
"""
if not target_id:
return self.current_target
return await self.current_context.get_target(target_id=target_id, timeout=timeout)
async def get_target_for_iframe(self, iframe: WebElement) -> Target:
"""
get the Target for a specific iframe
.. warning::
only cross-iframes have a Target due to `OOPIF <https://www.chromium.org/developers/design-documents/oop-iframes/>`__. See `site-isolation <https://www.chromium.org/Home/chromium-security/site-isolation/>`__
For a general solution, have a look at ``WebElement.content_document`` instead
:param iframe: the iframe to get the Target for
"""
return await self.current_target.get_target_for_iframe(iframe=iframe)
async def get_targets_for_iframes(self, iframes: typing.List[WebElement]) -> typing.List[Target]:
"""
returns a list of targets for iframes
see ``webdriver.Chrome.get_target_for_iframe`` for more information
:param iframes: the iframe to get the targets for
"""
return await self.current_target.get_targets_for_iframes(iframes=iframes)
async def wait_download(self, timeout: float or None = 30) -> dict:
"""
wait for a download on the current tab
returns something like
.. code-block:: python
{
"frameId": "2D543B5E8B14945B280C537A4882A695",
"guid": "c91df4d5-9b45-4962-84df-3749bd3f926d",
"url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
"suggestedFilename": "dummy.pdf",
# only if options.downloads_dir specified
"guid_file": "D:\\System\\AppData\\PyCharm\\scratches\\downloads\\c91df4d5-9b45-4962-84df-3749bd3f926d"
}
:param timeout: time in seconds to wait for a download
.. warning::
downloads from iframes not supported yet
"""
return await self.current_target.wait_download(timeout=timeout)
async def get(self, url: str, referrer: str = None, wait_load: bool = True, timeout: float = 30) -> typing.Union[
None, dict]:
"""Loads a web page in the current Target
:param url: the url to load.
:param referrer: the referrer to load the page with
:param wait_load: whether to wait for the webpage to load
:param timeout: the maximum time in seconds for waiting on load
returns the same as :func:`Target.wait_download <selenium_driverless.types.target.Target.wait_download>` if the url initiates a download
"""
return await self.current_target.get(url=url, referrer=referrer, wait_load=wait_load, timeout=timeout)
@property
async def title(self) -> str:
"""**async** the title of the current target"""
target = await self.current_target_info
return target.title
@property
def current_pointer(self) -> Pointer:
"""the :class:`Pointer <selenium_driverless.input.pointer.Pointer>` for this target"""
target = self.current_target
return target.pointer
async def send_keys(self, text: str):
"""
send text & keys to the current target
:param text: the text to send
"""
await self.current_target.send_keys(text)
async def execute_raw_script(self, script: str, *args, await_res: bool = False,
serialization: typing.Literal["deep", "json", "idOnly"] = "deep",
max_depth: int = None, timeout: float = 2, execution_context_id,
unique_context: bool = True):
"""executes a JavaScript on ``GlobalThis`` such as
.. code-block:: js
function(...arguments){return document}
:param script: the script as a string
:param args: the argument which are passed to the function. Those can be either json-serializable or a RemoteObject such as WebElement
:param await_res: whether to await the function or the return value of it
:param serialization: can be one of ``deep``, ``json``, ``idOnly``
:param max_depth: The maximum depth objects get serialized.
:param timeout: the maximum time to wait for the execution to complete
:param execution_context_id: the execution context id to run the JavaScript in. Exclusive with unique_context
:param unique_context: whether to use an isolated context to run the Script in.
see `Runtime.callFunctionOn <https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-callFunctionOn>`_
"""
return await self.current_target.execute_raw_script(script, *args, await_res=await_res,
serialization=serialization, max_depth=max_depth,
timeout=timeout, execution_context_id=execution_context_id,
unique_context=unique_context)
async def execute_script(self, script: str, *args, max_depth: int = 2, serialization: str = None,
timeout: float = 2, execution_context_id: str = None,
unique_context: bool = True):
"""executes JavaScript synchronously on ``GlobalThis`` such as
.. code-block:: js
return document
see :func:`Target.execute_raw_script <selenium_driverless.types.target.Target.execute_raw_script>` for argument descriptions
"""
return await self.current_target.execute_script(script, *args, max_depth=max_depth, serialization=serialization,
timeout=timeout, execution_context_id=execution_context_id,
unique_context=unique_context)
async def execute_async_script(self, script: str, *args, max_depth: int = 2,
serialization: str = None, timeout: float = 2, execution_context_id: str = None,
unique_context: bool = True):
"""executes JavaScript asynchronously on ``GlobalThis`` such as
.. warning::
using execute_async_script is not recommended as it doesn't handle exceptions correctly.
Use :func:`Chrome.eval_async <selenium_driverless.webdriver.Chrome.eval_async>`
.. code-block:: js
resolve = arguments[arguments.length-1]
see :func:`Target.execute_raw_script <selenium_driverless.types.target.Target.execute_raw_script>` for argument descriptions
"""
return await self.current_target.execute_async_script(script, *args, max_depth=max_depth,
serialization=serialization,
timeout=timeout,
execution_context_id=execution_context_id,
unique_context=unique_context)
async def eval_async(self, script: str, *args, max_depth: int = 2,
serialization: str = None, timeout: float = 2, execution_context_id: str = None,
unique_context: bool = True):
"""executes JavaScript asynchronously on ``GlobalThis`` such as
.. code-block:: js
res = await fetch("https://httpbin.org/get");
// mind CORS!
json = await res.json()
return json
see :func:`Target.execute_raw_script <selenium_driverless.types.target.Target.execute_raw_script>` for argument descriptions
"""
return await self.current_target.eval_async(script, *args, max_depth=max_depth, serialization=serialization,
timeout=timeout,
execution_context_id=execution_context_id,
unique_context=unique_context)
@property
async def current_url(self) -> str:
"""**async** current URL of the current Target
"""
target = self.current_target
return await target.url
@property
async def page_source(self) -> str:
"""**async** html of the current page.
"""
target = self.current_target
return await target.page_source
async def close(self, timeout: float = 2) -> None:
"""Closes the current target (only works for tabs).
:param timeout: timeout in seconds for the tab to close
"""
await self.current_target.close(timeout=timeout)
async def focus(self):
"""focuses the current target (only works for tabs)
"""
await self.current_target.focus()
async def quit(self, timeout: float = 30, clean_dirs: bool = True) -> None:
"""Closes Chrome
:param timeout: the maximum time waiting for chrome to quit correctly
:param clean_dirs: whether to clean out the user-data-dir directory
"""
from selenium_driverless import EXC_HANDLER
loop = asyncio.get_running_loop()
def clean_dirs_sync(dirs: typing.List[str]):
for _dir in dirs:
while os.path.isdir(_dir):
shutil.rmtree(_dir, ignore_errors=True)
if self._started:
start = time.perf_counter()
# noinspection PyUnresolvedReferences
try:
# assumption: chrome is still running
await self.base_target.execute_cdp_cmd("Browser.close", timeout=7)
except websockets.ConnectionClosedError:
pass
except Exception as e:
EXC_HANDLER(e)
if not self._is_remote:
if self._process is not None:
# assumption: chrome is being shutdown manually or programmatically
try:
await loop.run_in_executor(None, lambda: self._process.wait(timeout))
except Exception as e:
EXC_HANDLER(e)
else:
self._process = None
try:
# assumption: chrome hasn't closed within timeout, killing with force
# wait for process to be killed
if self._process is not None:
if os.name == 'posix':
os.killpg(os.getpgid(self._process.pid), signal.SIGTERM)
else:
self._process.terminate()
try:
await loop.run_in_executor(None, lambda: self._process.wait(timeout))
except subprocess.TimeoutExpired:
if os.name == 'posix':
os.killpg(os.getpgid(self._process.pid), signal.SIGKILL)
else:
self._process.kill()
except Exception as e:
EXC_HANDLER(e)
finally:
self._started = False
if self._stderr_file:
try:
self._stderr.close()
except Exception as e:
EXC_HANDLER(e)
# clean temp dir for extensions etc
try:
await asyncio.wait_for(
# wait for
loop.run_in_executor(None,
lambda: clean_dirs_sync(
[self._temp_dir])),
timeout=max(5, int(timeout - (time.perf_counter() - start))))
except Exception as e:
EXC_HANDLER(e)
if clean_dirs:
# clean user-data-dir for chrome
try:
await asyncio.wait_for(
# wait for
loop.run_in_executor(None,
lambda: clean_dirs_sync(
[self._options.user_data_dir])),
timeout=max(5, int(timeout - (time.perf_counter() - start))))
except Exception as e:
warnings.warn(
"driver hasn't quit correctly, "
"files might be left in your temp folder & chrome might still be running",
ResourceWarning)
raise e
def __del__(self):
try:
if self._started:
warnings.warn(
"driver hasn't quit correctly, "
"files might be left in your temp folder & chrome might still be running",
ResourceWarning)
except AttributeError:
pass
@property
async def current_target_info(self) -> TargetInfo:
"""**async** TargetInfo of the current target"""
return await self.current_target.info
@property
def current_window_handle(self) -> str:
"""current TargetId
.. warning::
this is deprecated and will be removed
use ``webdriver.Chrome.current_target.id`` instead
"""
warnings.warn(f'"webdriver.Chrome.current_window_handle" is deprecated and will be removed\n'
'use "webdriver.Chrome.current_target.id" instead', DeprecationWarning)
if self.current_target:
return self.current_target.id
@property
async def current_window_id(self):
"""**async** the ``WindowId`` of the window the current Target belongs to
"""
result = await self.execute_cdp_cmd("Browser.getWindowForTarget", {"targetId": self.current_target.id})
return result["windowId"]
@property
async def window_handles(self) -> List[TargetInfo]:
"""**async** TargetInfo on all tabs in the current context
.. warning::
the tabs aren't ordered by position in the window. Do not rely on the index, but iterate and filter them.
"""
warnings.warn(
"the tabs aren't ordered by position in the window. Do not rely on the index, but iterate and filter them.")
tabs = []
targets = await self.targets
for info in list(targets.values()):
if info.type == "page":
tabs.append(info)
return tabs
async def new_window(self, type_hint: typing.Literal["tab", "window"] = "tab", url="",
activate: bool = True) -> Target:
"""Creates a new window or tab in the current context
:param type_hint: whether to create a tab or window
:param url: the url which the new window should start on. Defaults to about:blank
:param activate: whether to explicitly activate/focus the window
.. code-block:: python
new_target = driver.new_window('tab')
"""
return await self.current_context.new_window(type_hint=type_hint, url=url, activate=activate)
async def set_window_state(self, state: typing.Literal["normal", "minimized", "maximized", "fullscreen"]):
"""sets the window state on the window the current Target belongs to
:param state: the state to set
"""
window_id = await self.current_window_id
bounds = {"windowState": state}
await self.execute_cdp_cmd("Browser.setWindowBounds", {"bounds": bounds, "windowId": window_id})
async def normalize_window(self):
"""Normalizes the window position and size on the window the current Target belongs to
"""
await self.set_window_state("normal")
async def maximize_window(self) -> None:
"""Maximizes the window the current Target belongs to"""
await self.set_window_state("maximized")
async def fullscreen_window(self) -> None:
"""enters fullscreen on the window the current Target belongs to"""
await self.set_window_state("fullscreen")
async def minimize_window(self) -> None:
"""minimizes the window the current Target belongs to.
.. warning::
Minimizing isn't recommended as it can throttle some functionalities in chrome.
"""
await self.set_window_state("minimized")
# noinspection PyUnusedLocal
async def print_page(self) -> str:
"""Prints the page (current target => tab) to PDF
"""
target = self.current_target
return await target.print_page()
@property
def switch_to(self) -> SwitchTo:
"""SwitchTo handle
"""
return self.current_context.switch_to
# Navigation
async def back(self) -> None:
"""Goes one step backward in the browser history on the current target (has to be a tab).
"""
await self.current_target.back()
async def forward(self) -> None:
"""Goes one step forward in the browser history on the current target (has to be a tab).
"""
await self.current_target.forward()