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