Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/py/selenium/webdriver/remote/webelement.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
from __future__ import annotations
18
19
import os
20
import pkgutil
21
import warnings
22
import zipfile
23
from abc import ABCMeta
24
from base64 import b64decode, encodebytes
25
from hashlib import md5 as md5_hash
26
from io import BytesIO
27
28
from selenium.common.exceptions import JavascriptException, WebDriverException
29
from selenium.webdriver.common.by import By
30
from selenium.webdriver.common.utils import keys_to_typing
31
32
from .command import Command
33
from .shadowroot import ShadowRoot
34
35
# TODO: When moving to supporting python 3.9 as the minimum version we can
36
# use built in importlib_resources.files.
37
getAttribute_js = None
38
isDisplayed_js = None
39
40
41
def _load_js():
42
global getAttribute_js
43
global isDisplayed_js
44
_pkg = ".".join(__name__.split(".")[:-1])
45
getAttribute_js = pkgutil.get_data(_pkg, "getAttribute.js").decode("utf8")
46
isDisplayed_js = pkgutil.get_data(_pkg, "isDisplayed.js").decode("utf8")
47
48
49
class BaseWebElement(metaclass=ABCMeta):
50
"""Abstract Base Class for WebElement.
51
52
ABC's will allow custom types to be registered as a WebElement to
53
pass type checks.
54
"""
55
56
pass
57
58
59
class WebElement(BaseWebElement):
60
"""Represents a DOM element.
61
62
Generally, all interesting operations that interact with a document will be
63
performed through this interface.
64
65
All method calls will do a freshness check to ensure that the element
66
reference is still valid. This essentially determines whether the
67
element is still attached to the DOM. If this test fails, then an
68
``StaleElementReferenceException`` is thrown, and all future calls to this
69
instance will fail.
70
"""
71
72
def __init__(self, parent, id_) -> None:
73
self._parent = parent
74
self._id = id_
75
76
def __repr__(self):
77
return f'<{type(self).__module__}.{type(self).__name__} (session="{self.session_id}", element="{self._id}")>'
78
79
@property
80
def session_id(self) -> str:
81
return self._parent.session_id
82
83
@property
84
def tag_name(self) -> str:
85
"""This element's ``tagName`` property.
86
87
Returns:
88
--------
89
str : The tag name of the element.
90
91
Example:
92
--------
93
>>> element = driver.find_element(By.ID, "foo")
94
"""
95
return self._execute(Command.GET_ELEMENT_TAG_NAME)["value"]
96
97
@property
98
def text(self) -> str:
99
"""The text of the element.
100
101
Returns:
102
--------
103
str : The text of the element.
104
105
Example:
106
--------
107
>>> element = driver.find_element(By.ID, "foo")
108
>>> print(element.text)
109
"""
110
return self._execute(Command.GET_ELEMENT_TEXT)["value"]
111
112
def click(self) -> None:
113
"""Clicks the element.
114
115
Example:
116
--------
117
>>> element = driver.find_element(By.ID, "foo")
118
>>> element.click()
119
"""
120
self._execute(Command.CLICK_ELEMENT)
121
122
def submit(self) -> None:
123
"""Submits a form.
124
125
Example:
126
--------
127
>>> form = driver.find_element(By.NAME, "login")
128
>>> form.submit()
129
"""
130
script = (
131
"/* submitForm */var form = arguments[0];\n"
132
'while (form.nodeName != "FORM" && form.parentNode) {\n'
133
" form = form.parentNode;\n"
134
"}\n"
135
"if (!form) { throw Error('Unable to find containing form element'); }\n"
136
"if (!form.ownerDocument) { throw Error('Unable to find owning document'); }\n"
137
"var e = form.ownerDocument.createEvent('Event');\n"
138
"e.initEvent('submit', true, true);\n"
139
"if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }\n"
140
)
141
142
try:
143
self._parent.execute_script(script, self)
144
except JavascriptException as exc:
145
raise WebDriverException("To submit an element, it must be nested inside a form element") from exc
146
147
def clear(self) -> None:
148
"""Clears the text if it's a text entry element.
149
150
Example:
151
--------
152
>>> text_field = driver.find_element(By.NAME, "username")
153
>>> text_field.clear()
154
"""
155
self._execute(Command.CLEAR_ELEMENT)
156
157
def get_property(self, name) -> str | bool | WebElement | dict:
158
"""Gets the given property of the element.
159
160
Parameters:
161
-----------
162
name : str
163
- Name of the property to retrieve.
164
165
Returns:
166
-------
167
str | bool | WebElement | dict : The value of the property.
168
169
Example:
170
-------
171
>>> text_length = target_element.get_property("text_length")
172
"""
173
try:
174
return self._execute(Command.GET_ELEMENT_PROPERTY, {"name": name})["value"]
175
except WebDriverException:
176
# if we hit an end point that doesn't understand getElementProperty lets fake it
177
return self.parent.execute_script("return arguments[0][arguments[1]]", self, name)
178
179
def get_dom_attribute(self, name) -> str:
180
"""Gets the given attribute of the element. Unlike
181
:func:`~selenium.webdriver.remote.BaseWebElement.get_attribute`, this
182
method only returns attributes declared in the element's HTML markup.
183
184
Parameters:
185
-----------
186
name : str
187
- Name of the attribute to retrieve.
188
189
Returns:
190
-------
191
str : The value of the attribute.
192
193
Example:
194
-------
195
>>> text_length = target_element.get_dom_attribute("class")
196
"""
197
return self._execute(Command.GET_ELEMENT_ATTRIBUTE, {"name": name})["value"]
198
199
def get_attribute(self, name) -> str | None:
200
"""Gets the given attribute or property of the element.
201
202
This method will first try to return the value of a property with the
203
given name. If a property with that name doesn't exist, it returns the
204
value of the attribute with the same name. If there's no attribute with
205
that name, ``None`` is returned.
206
207
Values which are considered truthy, that is equals "true" or "false",
208
are returned as booleans. All other non-``None`` values are returned
209
as strings. For attributes or properties which do not exist, ``None``
210
is returned.
211
212
To obtain the exact value of the attribute or property,
213
use :func:`~selenium.webdriver.remote.BaseWebElement.get_dom_attribute` or
214
:func:`~selenium.webdriver.remote.BaseWebElement.get_property` methods respectively.
215
216
Parameters:
217
-----------
218
name : str
219
- Name of the attribute/property to retrieve.
220
221
Returns:
222
-------
223
str | bool | None : The value of the attribute/property.
224
225
Example:
226
--------
227
>>> # Check if the "active" CSS class is applied to an element.
228
>>> is_active = "active" in target_element.get_attribute("class")
229
"""
230
if getAttribute_js is None:
231
_load_js()
232
attribute_value = self.parent.execute_script(
233
f"/* getAttribute */return ({getAttribute_js}).apply(null, arguments);", self, name
234
)
235
return attribute_value
236
237
def is_selected(self) -> bool:
238
"""Returns whether the element is selected.
239
240
Example:
241
--------
242
>>> is_selected = element.is_selected()
243
244
Notes:
245
------
246
- This method is generally used on checkboxes, options in a select
247
and radio buttons.
248
"""
249
return self._execute(Command.IS_ELEMENT_SELECTED)["value"]
250
251
def is_enabled(self) -> bool:
252
"""Returns whether the element is enabled.
253
254
Example:
255
--------
256
>>> is_enabled = element.is_enabled()
257
"""
258
return self._execute(Command.IS_ELEMENT_ENABLED)["value"]
259
260
def send_keys(self, *value: str) -> None:
261
"""Simulates typing into the element.
262
263
Parameters:
264
-----------
265
value : str
266
- A string for typing, or setting form fields. For setting
267
file inputs, this could be a local file path.
268
269
Notes:
270
------
271
- Use this to send simple key events or to fill out form fields
272
- This can also be used to set file inputs.
273
274
Examples:
275
--------
276
To send a simple key event::
277
>>> form_textfield = driver.find_element(By.NAME, "username")
278
>>> form_textfield.send_keys("admin")
279
280
or to set a file input field::
281
>>> file_input = driver.find_element(By.NAME, "profilePic")
282
>>> file_input.send_keys("path/to/profilepic.gif")
283
>>> # Generally it's better to wrap the file path in one of the methods
284
>>> # in os.path to return the actual path to support cross OS testing.
285
>>> # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
286
>>> # When using Cygwin, the path need to be provided in Windows format.
287
>>> # file_input.send_keys(f"C:/cygwin{os.path.abspath('path/to/profilepic.gif').replace('/', '\\')}")
288
"""
289
# transfer file to another machine only if remote driver is used
290
# the same behaviour as for java binding
291
if self.parent._is_remote:
292
local_files = list(
293
map(
294
lambda keys_to_send: self.parent.file_detector.is_local_file(str(keys_to_send)),
295
"".join(map(str, value)).split("\n"),
296
)
297
)
298
if None not in local_files:
299
remote_files = []
300
for file in local_files:
301
remote_files.append(self._upload(file))
302
value = tuple("\n".join(remote_files))
303
304
self._execute(
305
Command.SEND_KEYS_TO_ELEMENT, {"text": "".join(keys_to_typing(value)), "value": keys_to_typing(value)}
306
)
307
308
@property
309
def shadow_root(self) -> ShadowRoot:
310
"""Returns a shadow root of the element if there is one or an error.
311
Only works from Chromium 96, Firefox 96, and Safari 16.4 onwards.
312
313
Returns:
314
-------
315
ShadowRoot : object
316
317
Raises:
318
-------
319
NoSuchShadowRoot - if no shadow root was attached to element
320
321
Example:
322
--------
323
>>> try:
324
... shadow_root = element.shadow_root
325
>>> except NoSuchShadowRoot:
326
... print("No shadow root attached to element")
327
"""
328
return self._execute(Command.GET_SHADOW_ROOT)["value"]
329
330
# RenderedWebElement Items
331
def is_displayed(self) -> bool:
332
"""Whether the element is visible to a user.
333
334
Example:
335
--------
336
>>> is_displayed = element.is_displayed()
337
"""
338
# Only go into this conditional for browsers that don't use the atom themselves
339
if isDisplayed_js is None:
340
_load_js()
341
return self.parent.execute_script(f"/* isDisplayed */return ({isDisplayed_js}).apply(null, arguments);", self)
342
343
@property
344
def location_once_scrolled_into_view(self) -> dict:
345
"""THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where
346
on the screen an element is so that we can click it. This method should
347
cause the element to be scrolled into view.
348
349
Returns:
350
--------
351
dict: the top lefthand corner location on the screen, or zero
352
coordinates if the element is not visible.
353
354
Example:
355
--------
356
>>> loc = element.location_once_scrolled_into_view
357
"""
358
old_loc = self._execute(
359
Command.W3C_EXECUTE_SCRIPT,
360
{
361
"script": "arguments[0].scrollIntoView(true); return arguments[0].getBoundingClientRect()",
362
"args": [self],
363
},
364
)["value"]
365
return {"x": round(old_loc["x"]), "y": round(old_loc["y"])}
366
367
@property
368
def size(self) -> dict:
369
"""The size of the element.
370
371
Returns:
372
--------
373
dict: The width and height of the element.
374
375
Example:
376
--------
377
>>> size = element.size
378
"""
379
size = self._execute(Command.GET_ELEMENT_RECT)["value"]
380
new_size = {"height": size["height"], "width": size["width"]}
381
return new_size
382
383
def value_of_css_property(self, property_name) -> str:
384
"""The value of a CSS property.
385
386
Parameters:
387
-----------
388
property_name : str
389
- The name of the CSS property to get the value of.
390
391
Returns:
392
--------
393
str : The value of the CSS property.
394
395
Example:
396
--------
397
>>> value = element.value_of_css_property("color")
398
"""
399
return self._execute(Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, {"propertyName": property_name})["value"]
400
401
@property
402
def location(self) -> dict:
403
"""The location of the element in the renderable canvas.
404
405
Returns:
406
--------
407
dict: The x and y coordinates of the element.
408
409
Example:
410
--------
411
>>> loc = element.location
412
"""
413
old_loc = self._execute(Command.GET_ELEMENT_RECT)["value"]
414
new_loc = {"x": round(old_loc["x"]), "y": round(old_loc["y"])}
415
return new_loc
416
417
@property
418
def rect(self) -> dict:
419
"""A dictionary with the size and location of the element.
420
421
Returns:
422
--------
423
dict: The size and location of the element.
424
425
Example:
426
--------
427
>>> rect = element.rect
428
"""
429
return self._execute(Command.GET_ELEMENT_RECT)["value"]
430
431
@property
432
def aria_role(self) -> str:
433
"""Returns the ARIA role of the current web element.
434
435
Returns:
436
--------
437
str : The ARIA role of the element.
438
439
Example:
440
--------
441
>>> role = element.aria_role
442
"""
443
return self._execute(Command.GET_ELEMENT_ARIA_ROLE)["value"]
444
445
@property
446
def accessible_name(self) -> str:
447
"""Returns the ARIA Level of the current webelement.
448
449
Returns:
450
--------
451
str : The ARIA Level of the element.
452
453
Example:
454
--------
455
>>> name = element.accessible_name
456
"""
457
return self._execute(Command.GET_ELEMENT_ARIA_LABEL)["value"]
458
459
@property
460
def screenshot_as_base64(self) -> str:
461
"""Gets the screenshot of the current element as a base64 encoded
462
string.
463
464
Returns:
465
--------
466
str : The screenshot of the element as a base64 encoded string.
467
468
Example:
469
--------
470
>>> img_b64 = element.screenshot_as_base64
471
"""
472
return self._execute(Command.ELEMENT_SCREENSHOT)["value"]
473
474
@property
475
def screenshot_as_png(self) -> bytes:
476
"""Gets the screenshot of the current element as a binary data.
477
478
Returns:
479
--------
480
bytes : The screenshot of the element as binary data.
481
482
Example:
483
--------
484
>>> element_png = element.screenshot_as_png
485
"""
486
return b64decode(self.screenshot_as_base64.encode("ascii"))
487
488
def screenshot(self, filename) -> bool:
489
"""Saves a screenshot of the current element to a PNG image file.
490
Returns False if there is any IOError, else returns True. Use full
491
paths in your filename.
492
493
Returns:
494
--------
495
bool : True if the screenshot was saved successfully, False otherwise.
496
497
Parameters:
498
-----------
499
filename : str
500
The full path you wish to save your screenshot to. This
501
should end with a `.png` extension.
502
503
Element:
504
--------
505
>>> element.screenshot("/Screenshots/foo.png")
506
"""
507
if not filename.lower().endswith(".png"):
508
warnings.warn(
509
"name used for saved screenshot does not match file type. It should end with a `.png` extension",
510
UserWarning,
511
)
512
png = self.screenshot_as_png
513
try:
514
with open(filename, "wb") as f:
515
f.write(png)
516
except OSError:
517
return False
518
finally:
519
del png
520
return True
521
522
@property
523
def parent(self):
524
"""Internal reference to the WebDriver instance this element was found
525
from.
526
527
Example:
528
--------
529
>>> element = driver.find_element(By.ID, "foo")
530
>>> parent_element = element.parent
531
"""
532
return self._parent
533
534
@property
535
def id(self) -> str:
536
"""Internal ID used by selenium.
537
538
This is mainly for internal use. Simple use cases such as checking if 2
539
webelements refer to the same element, can be done using ``==``::
540
541
Example:
542
--------
543
>>> if element1 == element2:
544
... print("These 2 are equal")
545
"""
546
return self._id
547
548
def __eq__(self, element):
549
return hasattr(element, "id") and self._id == element.id
550
551
def __ne__(self, element):
552
return not self.__eq__(element)
553
554
# Private Methods
555
def _execute(self, command, params=None):
556
"""Executes a command against the underlying HTML element.
557
558
Parameters:
559
-----------
560
command : any
561
The name of the command to _execute as a string.
562
563
params : dict
564
A dictionary of named Parameters to send with the command.
565
566
Returns:
567
-------
568
The command's JSON response loaded into a dictionary object.
569
"""
570
if not params:
571
params = {}
572
params["id"] = self._id
573
return self._parent.execute(command, params)
574
575
def find_element(self, by=By.ID, value=None) -> WebElement:
576
"""Find an element given a By strategy and locator.
577
578
Parameters:
579
-----------
580
by : selenium.webdriver.common.by.By
581
The locating strategy to use. Default is `By.ID`. Supported values include:
582
- By.ID: Locate by element ID.
583
- By.NAME: Locate by the `name` attribute.
584
- By.XPATH: Locate by an XPath expression.
585
- By.CSS_SELECTOR: Locate by a CSS selector.
586
- By.CLASS_NAME: Locate by the `class` attribute.
587
- By.TAG_NAME: Locate by the tag name (e.g., "input", "button").
588
- By.LINK_TEXT: Locate a link element by its exact text.
589
- By.PARTIAL_LINK_TEXT: Locate a link element by partial text match.
590
- RelativeBy: Locate elements relative to a specified root element.
591
592
Example:
593
--------
594
element = driver.find_element(By.ID, 'foo')
595
596
Returns:
597
-------
598
WebElement
599
The first matching `WebElement` found on the page.
600
"""
601
by, value = self._parent.locator_converter.convert(by, value)
602
return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})["value"]
603
604
def find_elements(self, by=By.ID, value=None) -> list[WebElement]:
605
"""Find elements given a By strategy and locator.
606
607
Parameters:
608
-----------
609
by : selenium.webdriver.common.by.By
610
The locating strategy to use. Default is `By.ID`. Supported values include:
611
- By.ID: Locate by element ID.
612
- By.NAME: Locate by the `name` attribute.
613
- By.XPATH: Locate by an XPath expression.
614
- By.CSS_SELECTOR: Locate by a CSS selector.
615
- By.CLASS_NAME: Locate by the `class` attribute.
616
- By.TAG_NAME: Locate by the tag name (e.g., "input", "button").
617
- By.LINK_TEXT: Locate a link element by its exact text.
618
- By.PARTIAL_LINK_TEXT: Locate a link element by partial text match.
619
- RelativeBy: Locate elements relative to a specified root element.
620
621
Example:
622
--------
623
>>> element = driver.find_elements(By.ID, "foo")
624
625
Returns:
626
-------
627
List[WebElement]
628
list of `WebElements` matching locator strategy found on the page.
629
"""
630
by, value = self._parent.locator_converter.convert(by, value)
631
return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})["value"]
632
633
def __hash__(self) -> int:
634
return int(md5_hash(self._id.encode("utf-8")).hexdigest(), 16)
635
636
def _upload(self, filename):
637
fp = BytesIO()
638
zipped = zipfile.ZipFile(fp, "w", zipfile.ZIP_DEFLATED)
639
zipped.write(filename, os.path.split(filename)[1])
640
zipped.close()
641
content = encodebytes(fp.getvalue())
642
if not isinstance(content, str):
643
content = content.decode("utf-8")
644
try:
645
return self._execute(Command.UPLOAD_FILE, {"file": content})["value"]
646
except WebDriverException as e:
647
if "Unrecognized command: POST" in str(e):
648
return filename
649
if "Command not found: POST " in str(e):
650
return filename
651
if '{"status":405,"value":["GET","HEAD","DELETE"]}' in str(e):
652
return filename
653
raise
654
655