Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/py/selenium/webdriver/firefox/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
import base64
18
import os
19
import warnings
20
import zipfile
21
from contextlib import contextmanager
22
from io import BytesIO
23
from typing import Optional
24
25
from selenium.webdriver.common.driver_finder import DriverFinder
26
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
27
28
from .options import Options
29
from .remote_connection import FirefoxRemoteConnection
30
from .service import Service
31
32
33
class WebDriver(RemoteWebDriver):
34
"""Controls the GeckoDriver and allows you to drive the browser."""
35
36
CONTEXT_CHROME = "chrome"
37
CONTEXT_CONTENT = "content"
38
39
def __init__(
40
self,
41
options: Optional[Options] = None,
42
service: Optional[Service] = None,
43
keep_alive: bool = True,
44
) -> None:
45
"""Creates a new instance of the Firefox driver. Starts the service and
46
then creates new instance of Firefox driver.
47
48
:Args:
49
- options - Instance of ``options.Options``.
50
- service - (Optional) service instance for managing the starting and stopping of the driver.
51
- keep_alive - Whether to configure remote_connection.RemoteConnection to use HTTP keep-alive.
52
"""
53
54
self.service = service if service else Service()
55
options = options if options else Options()
56
57
finder = DriverFinder(self.service, options)
58
if finder.get_browser_path():
59
options.binary_location = finder.get_browser_path()
60
options.browser_version = None
61
62
self.service.path = self.service.env_path() or finder.get_driver_path()
63
self.service.start()
64
65
executor = FirefoxRemoteConnection(
66
remote_server_addr=self.service.service_url,
67
keep_alive=keep_alive,
68
ignore_proxy=options._ignore_local_proxy,
69
)
70
71
try:
72
super().__init__(command_executor=executor, options=options)
73
except Exception:
74
self.quit()
75
raise
76
77
self._is_remote = False
78
79
def quit(self) -> None:
80
"""Closes the browser and shuts down the GeckoDriver executable."""
81
try:
82
super().quit()
83
except Exception:
84
# We don't care about the message because something probably has gone wrong
85
pass
86
finally:
87
self.service.stop()
88
89
def set_context(self, context) -> None:
90
self.execute("SET_CONTEXT", {"context": context})
91
92
@contextmanager
93
def context(self, context):
94
"""Sets the context that Selenium commands are running in using a
95
`with` statement. The state of the context on the server is saved
96
before entering the block, and restored upon exiting it.
97
98
:param context: Context, may be one of the class properties
99
`CONTEXT_CHROME` or `CONTEXT_CONTENT`.
100
101
Usage example::
102
103
with selenium.context(selenium.CONTEXT_CHROME):
104
# chrome scope
105
... do stuff ...
106
"""
107
initial_context = self.execute("GET_CONTEXT").pop("value")
108
self.set_context(context)
109
try:
110
yield
111
finally:
112
self.set_context(initial_context)
113
114
def install_addon(self, path, temporary=False) -> str:
115
"""Installs Firefox addon.
116
117
Returns identifier of installed addon. This identifier can later
118
be used to uninstall addon.
119
120
:param temporary: allows you to load browser extensions temporarily during a session
121
:param path: Absolute path to the addon that will be installed.
122
123
:Usage:
124
::
125
126
driver.install_addon("/path/to/firebug.xpi")
127
"""
128
129
if os.path.isdir(path):
130
fp = BytesIO()
131
# filter all trailing slash found in path
132
path = os.path.normpath(path)
133
# account for trailing slash that will be added by os.walk()
134
path_root = len(path) + 1
135
with zipfile.ZipFile(fp, "w", zipfile.ZIP_DEFLATED, strict_timestamps=False) as zipped:
136
for base, _, files in os.walk(path):
137
for fyle in files:
138
filename = os.path.join(base, fyle)
139
zipped.write(filename, filename[path_root:])
140
addon = base64.b64encode(fp.getvalue()).decode("UTF-8")
141
else:
142
with open(path, "rb") as file:
143
addon = base64.b64encode(file.read()).decode("UTF-8")
144
145
payload = {"addon": addon, "temporary": temporary}
146
return self.execute("INSTALL_ADDON", payload)["value"]
147
148
def uninstall_addon(self, identifier) -> None:
149
"""Uninstalls Firefox addon using its identifier.
150
151
:Usage:
152
::
153
154
driver.uninstall_addon("[email protected]")
155
"""
156
self.execute("UNINSTALL_ADDON", {"id": identifier})
157
158
def get_full_page_screenshot_as_file(self, filename) -> bool:
159
"""Saves a full document screenshot of the current window to a PNG
160
image file. Returns False if there is any IOError, else returns True.
161
Use full paths in your filename.
162
163
:Args:
164
- filename: The full path you wish to save your screenshot to. This
165
should end with a `.png` extension.
166
167
:Usage:
168
::
169
170
driver.get_full_page_screenshot_as_file("/Screenshots/foo.png")
171
"""
172
if not filename.lower().endswith(".png"):
173
warnings.warn(
174
"name used for saved screenshot does not match file type. It should end with a `.png` extension",
175
UserWarning,
176
)
177
png = self.get_full_page_screenshot_as_png()
178
try:
179
with open(filename, "wb") as f:
180
f.write(png)
181
except OSError:
182
return False
183
finally:
184
del png
185
return True
186
187
def save_full_page_screenshot(self, filename) -> bool:
188
"""Saves a full document screenshot of the current window to a PNG
189
image file. Returns False if there is any IOError, else returns True.
190
Use full paths in your filename.
191
192
:Args:
193
- filename: The full path you wish to save your screenshot to. This
194
should end with a `.png` extension.
195
196
:Usage:
197
::
198
199
driver.save_full_page_screenshot("/Screenshots/foo.png")
200
"""
201
return self.get_full_page_screenshot_as_file(filename)
202
203
def get_full_page_screenshot_as_png(self) -> bytes:
204
"""Gets the full document screenshot of the current window as a binary
205
data.
206
207
:Usage:
208
::
209
210
driver.get_full_page_screenshot_as_png()
211
"""
212
return base64.b64decode(self.get_full_page_screenshot_as_base64().encode("ascii"))
213
214
def get_full_page_screenshot_as_base64(self) -> str:
215
"""Gets the full document screenshot of the current window as a base64
216
encoded string which is useful in embedded images in HTML.
217
218
:Usage:
219
::
220
221
driver.get_full_page_screenshot_as_base64()
222
"""
223
return self.execute("FULL_PAGE_SCREENSHOT")["value"]
224
225
def download_file(self, *args, **kwargs):
226
raise NotImplementedError
227
228
def get_downloadable_files(self, *args, **kwargs):
229
raise NotImplementedError
230
231