Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/py/selenium/webdriver/chromium/webdriver.py
3987 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 selenium.webdriver.chromium.options import ChromiumOptions
19
from selenium.webdriver.chromium.remote_connection import ChromiumRemoteConnection
20
from selenium.webdriver.chromium.service import ChromiumService
21
from selenium.webdriver.common.driver_finder import DriverFinder
22
from selenium.webdriver.common.webdriver import LocalWebDriver
23
from selenium.webdriver.remote.command import Command
24
25
26
class ChromiumDriver(LocalWebDriver):
27
"""Control the WebDriver instance of ChromiumDriver and drive the browser."""
28
29
def __init__(
30
self,
31
browser_name: str,
32
vendor_prefix: str,
33
options: ChromiumOptions | None = None,
34
service: ChromiumService | None = None,
35
keep_alive: bool = True,
36
) -> None:
37
"""Create a new WebDriver instance, start the service, and create new ChromiumDriver instance.
38
39
Args:
40
browser_name: Browser name used when matching capabilities.
41
vendor_prefix: Company prefix to apply to vendor-specific WebDriver extension commands.
42
options: Instance of ChromiumOptions.
43
service: Service object for handling the browser driver if you need to pass extra details.
44
keep_alive: Whether to configure ChromiumRemoteConnection to use HTTP keep-alive.
45
"""
46
self.service = service if service else ChromiumService()
47
self.options = options if options else ChromiumOptions()
48
49
finder = DriverFinder(self.service, self.options)
50
if finder.get_browser_path():
51
self.options.binary_location = finder.get_browser_path()
52
self.options.browser_version = None
53
54
self.service.path = self.service.env_path() or finder.get_driver_path()
55
self.service.start()
56
57
executor = ChromiumRemoteConnection(
58
remote_server_addr=self.service.service_url,
59
browser_name=browser_name,
60
vendor_prefix=vendor_prefix,
61
keep_alive=keep_alive,
62
ignore_proxy=self.options._ignore_local_proxy,
63
)
64
65
try:
66
super().__init__(command_executor=executor, options=self.options)
67
except Exception:
68
self.quit()
69
raise
70
71
def launch_app(self, id):
72
"""Launches Chromium app specified by id.
73
74
Args:
75
id: The id of the Chromium app to launch.
76
"""
77
return self.execute("launchApp", {"id": id})
78
79
def get_network_conditions(self):
80
"""Gets Chromium network emulation settings.
81
82
Returns:
83
A dict. For example: {'latency': 4, 'download_throughput': 2, 'upload_throughput': 2}
84
"""
85
return self.execute("getNetworkConditions")["value"]
86
87
def set_network_conditions(self, **network_conditions) -> None:
88
"""Sets Chromium network emulation settings.
89
90
Args:
91
**network_conditions: A dict with conditions specification.
92
93
Example:
94
driver.set_network_conditions(
95
offline=False,
96
latency=5, # additional latency (ms)
97
download_throughput=500 * 1024, # maximal throughput
98
upload_throughput=500 * 1024,
99
) # maximal throughput
100
101
Note: `throughput` can be used to set both (for download and upload).
102
"""
103
self.execute("setNetworkConditions", {"network_conditions": network_conditions})
104
105
def delete_network_conditions(self) -> None:
106
"""Resets Chromium network emulation settings."""
107
self.execute("deleteNetworkConditions")
108
109
def set_permissions(self, name: str, value: str) -> None:
110
"""Sets Applicable Permission.
111
112
Args:
113
name: The item to set the permission on.
114
value: The value to set on the item
115
116
Example:
117
driver.set_permissions("clipboard-read", "denied")
118
"""
119
self.execute("setPermissions", {"descriptor": {"name": name}, "state": value})
120
121
def execute_cdp_cmd(self, cmd: str, cmd_args: dict):
122
"""Execute Chrome Devtools Protocol command and get returned result.
123
124
The command and command args should follow chrome devtools protocol domains/commands
125
126
See:
127
- https://chromedevtools.github.io/devtools-protocol/
128
129
Args:
130
cmd: A str, command name
131
cmd_args: A dict, command args. empty dict {} if there is no command args
132
133
Example:
134
`driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})`
135
136
Returns:
137
A dict, empty dict {} if there is no result to return.
138
For example to getResponseBody:
139
{'base64Encoded': False, 'body': 'response body string'}
140
"""
141
return super().execute_cdp_cmd(cmd, cmd_args)
142
143
def get_sinks(self) -> list:
144
"""Get a list of sinks available for Cast."""
145
return self.execute("getSinks")["value"]
146
147
def get_issue_message(self):
148
"""Returns an error message when there is any issue in a Cast session."""
149
return self.execute("getIssueMessage")["value"]
150
151
@property
152
def log_types(self):
153
"""Gets a list of the available log types.
154
155
Example:
156
--------
157
>>> driver.log_types
158
"""
159
return self.execute(Command.GET_AVAILABLE_LOG_TYPES)["value"]
160
161
def get_log(self, log_type):
162
"""Gets the log for a given log type.
163
164
Args:
165
log_type: Type of log that which will be returned
166
167
Example:
168
>>> driver.get_log("browser")
169
>>> driver.get_log("driver")
170
>>> driver.get_log("client")
171
>>> driver.get_log("server")
172
"""
173
return self.execute(Command.GET_LOG, {"type": log_type})["value"]
174
175
def set_sink_to_use(self, sink_name: str) -> dict:
176
"""Set a specific sink as a Cast session receiver target.
177
178
Args:
179
sink_name: Name of the sink to use as the target.
180
"""
181
return self.execute("setSinkToUse", {"sinkName": sink_name})
182
183
def start_desktop_mirroring(self, sink_name: str) -> dict:
184
"""Starts a desktop mirroring session on a specific receiver target.
185
186
Args:
187
sink_name: Name of the sink to use as the target.
188
"""
189
return self.execute("startDesktopMirroring", {"sinkName": sink_name})
190
191
def start_tab_mirroring(self, sink_name: str) -> dict:
192
"""Starts a tab mirroring session on a specific receiver target.
193
194
Args:
195
sink_name: Name of the sink to use as the target.
196
"""
197
return self.execute("startTabMirroring", {"sinkName": sink_name})
198
199
def stop_casting(self, sink_name: str) -> dict:
200
"""Stops the existing Cast session on a specific receiver target.
201
202
Args:
203
sink_name: Name of the sink to stop the Cast session.
204
"""
205
return self.execute("stopCasting", {"sinkName": sink_name})
206
207