Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/py/selenium/webdriver/chromium/webdriver.py
1864 views
1
# Licensed to the Software Freedom Conservancy (SFC) under one
2
# or more contributor license agreements. See the NOTICE file
3
# distributed with this work for additional information
4
# regarding copyright ownership. The SFC licenses this file
5
# to you under the Apache License, Version 2.0 (the
6
# "License"); you may not use this file except in compliance
7
# with the License. You may obtain a copy of the License at
8
#
9
# http://www.apache.org/licenses/LICENSE-2.0
10
#
11
# Unless required by applicable law or agreed to in writing,
12
# software distributed under the License is distributed on an
13
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
# KIND, either express or implied. See the License for the
15
# specific language governing permissions and limitations
16
# under the License.
17
18
from typing import Optional
19
20
from selenium.webdriver.chromium.remote_connection import ChromiumRemoteConnection
21
from selenium.webdriver.common.driver_finder import DriverFinder
22
from selenium.webdriver.common.options import ArgOptions
23
from selenium.webdriver.common.service import Service
24
from selenium.webdriver.remote.command import Command
25
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
26
27
28
class ChromiumDriver(RemoteWebDriver):
29
"""Controls the WebDriver instance of ChromiumDriver and allows you to
30
drive the browser."""
31
32
def __init__(
33
self,
34
browser_name: Optional[str] = None,
35
vendor_prefix: Optional[str] = None,
36
options: ArgOptions = ArgOptions(),
37
service: Optional[Service] = None,
38
keep_alive: bool = True,
39
) -> None:
40
"""Creates a new WebDriver instance of the ChromiumDriver. Starts the
41
service and then creates new WebDriver instance of ChromiumDriver.
42
43
:Args:
44
- browser_name - Browser name used when matching capabilities.
45
- vendor_prefix - Company prefix to apply to vendor-specific WebDriver extension commands.
46
- options - this takes an instance of ChromiumOptions
47
- service - Service object for handling the browser driver if you need to pass extra details
48
- keep_alive - Whether to configure ChromiumRemoteConnection to use HTTP keep-alive.
49
"""
50
self.service = service
51
52
finder = DriverFinder(self.service, options)
53
if finder.get_browser_path():
54
options.binary_location = finder.get_browser_path()
55
options.browser_version = None
56
57
self.service.path = self.service.env_path() or finder.get_driver_path()
58
self.service.start()
59
60
executor = ChromiumRemoteConnection(
61
remote_server_addr=self.service.service_url,
62
browser_name=browser_name,
63
vendor_prefix=vendor_prefix,
64
keep_alive=keep_alive,
65
ignore_proxy=options._ignore_local_proxy,
66
)
67
68
try:
69
super().__init__(command_executor=executor, options=options)
70
except Exception:
71
self.quit()
72
raise
73
74
self._is_remote = False
75
76
def launch_app(self, id):
77
"""Launches Chromium app specified by id."""
78
return self.execute("launchApp", {"id": id})
79
80
def get_network_conditions(self):
81
"""Gets Chromium network emulation settings.
82
83
:Returns:
84
A dict.
85
For example: {'latency': 4, 'download_throughput': 2, 'upload_throughput': 2, 'offline': False}
86
"""
87
return self.execute("getNetworkConditions")["value"]
88
89
def set_network_conditions(self, **network_conditions) -> None:
90
"""Sets Chromium network emulation settings.
91
92
:Args:
93
- network_conditions: A dict with conditions specification.
94
95
:Usage:
96
::
97
98
driver.set_network_conditions(
99
offline=False,
100
latency=5, # additional latency (ms)
101
download_throughput=500 * 1024, # maximal throughput
102
upload_throughput=500 * 1024,
103
) # maximal throughput
104
105
Note: 'throughput' can be used to set both (for download and upload).
106
"""
107
self.execute("setNetworkConditions", {"network_conditions": network_conditions})
108
109
def delete_network_conditions(self) -> None:
110
"""Resets Chromium network emulation settings."""
111
self.execute("deleteNetworkConditions")
112
113
def set_permissions(self, name: str, value: str) -> None:
114
"""Sets Applicable Permission.
115
116
:Args:
117
- name: The item to set the permission on.
118
- value: The value to set on the item
119
120
:Usage:
121
::
122
123
driver.set_permissions("clipboard-read", "denied")
124
"""
125
self.execute("setPermissions", {"descriptor": {"name": name}, "state": value})
126
127
def execute_cdp_cmd(self, cmd: str, cmd_args: dict):
128
"""Execute Chrome Devtools Protocol command and get returned result The
129
command and command args should follow chrome devtools protocol
130
domains/commands, refer to link
131
https://chromedevtools.github.io/devtools-protocol/
132
133
:Args:
134
- cmd: A str, command name
135
- cmd_args: A dict, command args. empty dict {} if there is no command args
136
:Usage:
137
::
138
139
driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})
140
:Returns:
141
A dict, empty dict {} if there is no result to return.
142
For example to getResponseBody:
143
{'base64Encoded': False, 'body': 'response body string'}
144
"""
145
return super().execute_cdp_cmd(cmd, cmd_args)
146
147
def get_sinks(self) -> list:
148
""":Returns: A list of sinks available for Cast."""
149
return self.execute("getSinks")["value"]
150
151
def get_issue_message(self):
152
""":Returns: An error message when there is any issue in a Cast
153
session."""
154
return self.execute("getIssueMessage")["value"]
155
156
@property
157
def log_types(self):
158
"""Gets a list of the available log types.
159
160
Example:
161
--------
162
>>> driver.log_types
163
"""
164
return self.execute(Command.GET_AVAILABLE_LOG_TYPES)["value"]
165
166
def get_log(self, log_type):
167
"""Gets the log for a given log type.
168
169
Parameters:
170
-----------
171
log_type : str
172
- Type of log that which will be returned
173
174
Example:
175
--------
176
>>> driver.get_log("browser")
177
>>> driver.get_log("driver")
178
>>> driver.get_log("client")
179
>>> driver.get_log("server")
180
"""
181
return self.execute(Command.GET_LOG, {"type": log_type})["value"]
182
183
def set_sink_to_use(self, sink_name: str) -> dict:
184
"""Sets a specific sink, using its name, as a Cast session receiver
185
target.
186
187
:Args:
188
- sink_name: Name of the sink to use as the target.
189
"""
190
return self.execute("setSinkToUse", {"sinkName": sink_name})
191
192
def start_desktop_mirroring(self, sink_name: str) -> dict:
193
"""Starts a desktop mirroring session on a specific receiver target.
194
195
:Args:
196
- sink_name: Name of the sink to use as the target.
197
"""
198
return self.execute("startDesktopMirroring", {"sinkName": sink_name})
199
200
def start_tab_mirroring(self, sink_name: str) -> dict:
201
"""Starts a tab mirroring session on a specific receiver target.
202
203
:Args:
204
- sink_name: Name of the sink to use as the target.
205
"""
206
return self.execute("startTabMirroring", {"sinkName": sink_name})
207
208
def stop_casting(self, sink_name: str) -> dict:
209
"""Stops the existing Cast session on a specific receiver target.
210
211
:Args:
212
- sink_name: Name of the sink to stop the Cast session.
213
"""
214
return self.execute("stopCasting", {"sinkName": sink_name})
215
216
def quit(self) -> None:
217
"""Closes the browser and shuts down the ChromiumDriver executable."""
218
try:
219
super().quit()
220
except Exception:
221
# We don't care about the message because something probably has gone wrong
222
pass
223
finally:
224
self.service.stop()
225
226
def download_file(self, *args, **kwargs):
227
raise NotImplementedError
228
229
def get_downloadable_files(self, *args, **kwargs):
230
raise NotImplementedError
231
232