initial commit
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+77
@@ -0,0 +1,77 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
|
||||
class AbstractEventListener:
|
||||
"""Event listener must subclass and implement this fully or partially."""
|
||||
|
||||
def before_navigate_to(self, url: str, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_navigate_to(self, url: str, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_navigate_back(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_navigate_back(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_navigate_forward(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_navigate_forward(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_find(self, by, value, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_find(self, by, value, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_click(self, element, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_click(self, element, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_change_value_of(self, element, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_change_value_of(self, element, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_execute_script(self, script, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_execute_script(self, script, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_close(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_close(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def before_quit(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def after_quit(self, driver) -> None:
|
||||
pass
|
||||
|
||||
def on_exception(self, exception, driver) -> None:
|
||||
pass
|
||||
@@ -0,0 +1,326 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from re import Match
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import SupportsFloat, SupportsIndex, SupportsInt
|
||||
|
||||
ParseableFloat = SupportsFloat | SupportsIndex | str | bytes | bytearray
|
||||
ParseableInt = SupportsInt | SupportsIndex | str | bytes
|
||||
|
||||
|
||||
RGB_PATTERN = r"^\s*rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)\s*$"
|
||||
RGB_PCT_PATTERN = (
|
||||
r"^\s*rgb\(\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*\)\s*$"
|
||||
)
|
||||
RGBA_PATTERN = r"^\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0\.\d+)\s*\)\s*$"
|
||||
RGBA_PCT_PATTERN = (
|
||||
r"^\s*rgba\(\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,"
|
||||
+ r"\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(0|1|0\.\d+)\s*\)\s*$"
|
||||
)
|
||||
HEX_PATTERN = r"#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})"
|
||||
HEX3_PATTERN = r"#([A-Fa-f0-9])([A-Fa-f0-9])([A-Fa-f0-9])"
|
||||
HSL_PATTERN = r"^\s*hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)\s*$"
|
||||
HSLA_PATTERN = r"^\s*hsla\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*,\s*(0|1|0\.\d+)\s*\)\s*$"
|
||||
|
||||
|
||||
class Color:
|
||||
"""Color conversion support class.
|
||||
|
||||
Example:
|
||||
::
|
||||
|
||||
from selenium.webdriver.support.color import Color
|
||||
|
||||
print(Color.from_string("#00ff33").rgba)
|
||||
print(Color.from_string("rgb(1, 255, 3)").hex)
|
||||
print(Color.from_string("blue").rgba)
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def from_string(cls, str_: str) -> Color:
|
||||
import re
|
||||
|
||||
class Matcher:
|
||||
match_obj: Match[str] | None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.match_obj = None
|
||||
|
||||
def match(self, pattern: str, str_: str) -> Match[str] | None:
|
||||
self.match_obj = re.match(pattern, str_)
|
||||
return self.match_obj
|
||||
|
||||
@property
|
||||
def groups(self) -> Sequence[str]:
|
||||
return () if not self.match_obj else self.match_obj.groups()
|
||||
|
||||
m = Matcher()
|
||||
|
||||
if m.match(RGB_PATTERN, str_):
|
||||
return cls(*m.groups)
|
||||
if m.match(RGB_PCT_PATTERN, str_):
|
||||
rgb = tuple(float(each) / 100 * 255 for each in m.groups)
|
||||
return cls(*rgb)
|
||||
if m.match(RGBA_PATTERN, str_):
|
||||
return cls(*m.groups)
|
||||
if m.match(RGBA_PCT_PATTERN, str_):
|
||||
rgba = tuple([float(each) / 100 * 255 for each in m.groups[:3]] + [m.groups[3]])
|
||||
return cls(*rgba)
|
||||
if m.match(HEX_PATTERN, str_):
|
||||
rgb = tuple(int(each, 16) for each in m.groups)
|
||||
return cls(*rgb)
|
||||
if m.match(HEX3_PATTERN, str_):
|
||||
rgb = tuple(int(each * 2, 16) for each in m.groups)
|
||||
return cls(*rgb)
|
||||
if m.match(HSL_PATTERN, str_) or m.match(HSLA_PATTERN, str_):
|
||||
return cls._from_hsl(*m.groups)
|
||||
if str_.upper() in Colors:
|
||||
return Colors[str_.upper()]
|
||||
raise ValueError(f"Could not convert {str_} into color")
|
||||
|
||||
@classmethod
|
||||
def _from_hsl(cls, h: ParseableFloat, s: ParseableFloat, light: ParseableFloat, a: ParseableFloat = 1) -> Color:
|
||||
h = float(h) / 360
|
||||
s = float(s) / 100
|
||||
_l = float(light) / 100
|
||||
|
||||
if s == 0:
|
||||
r = _l
|
||||
g = r
|
||||
b = r
|
||||
else:
|
||||
luminocity2 = _l * (1 + s) if _l < 0.5 else _l + s - _l * s
|
||||
luminocity1 = 2 * _l - luminocity2
|
||||
|
||||
def hue_to_rgb(lum1: float, lum2: float, hue: float) -> float:
|
||||
if hue < 0.0:
|
||||
hue += 1
|
||||
if hue > 1.0:
|
||||
hue -= 1
|
||||
|
||||
if hue < 1.0 / 6.0:
|
||||
return lum1 + (lum2 - lum1) * 6.0 * hue
|
||||
if hue < 1.0 / 2.0:
|
||||
return lum2
|
||||
if hue < 2.0 / 3.0:
|
||||
return lum1 + (lum2 - lum1) * ((2.0 / 3.0) - hue) * 6.0
|
||||
return lum1
|
||||
|
||||
r = hue_to_rgb(luminocity1, luminocity2, h + 1.0 / 3.0)
|
||||
g = hue_to_rgb(luminocity1, luminocity2, h)
|
||||
b = hue_to_rgb(luminocity1, luminocity2, h - 1.0 / 3.0)
|
||||
|
||||
return cls(round(r * 255), round(g * 255), round(b * 255), a)
|
||||
|
||||
def __init__(self, red: ParseableInt, green: ParseableInt, blue: ParseableInt, alpha: ParseableFloat = 1) -> None:
|
||||
self.red = int(red)
|
||||
self.green = int(green)
|
||||
self.blue = int(blue)
|
||||
self.alpha = "1" if float(alpha) == 1 else str(float(alpha) or 0)
|
||||
|
||||
@property
|
||||
def rgb(self) -> str:
|
||||
return f"rgb({self.red}, {self.green}, {self.blue})"
|
||||
|
||||
@property
|
||||
def rgba(self) -> str:
|
||||
return f"rgba({self.red}, {self.green}, {self.blue}, {self.alpha})"
|
||||
|
||||
@property
|
||||
def hex(self) -> str:
|
||||
return f"#{self.red:02x}{self.green:02x}{self.blue:02x}"
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if isinstance(other, Color):
|
||||
return self.rgba == other.rgba
|
||||
return NotImplemented
|
||||
|
||||
def __ne__(self, other: Any) -> bool:
|
||||
result = self.__eq__(other)
|
||||
if result is NotImplemented:
|
||||
return result
|
||||
return not result
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash((self.red, self.green, self.blue, self.alpha))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Color(red={self.red}, green={self.green}, blue={self.blue}, alpha={self.alpha})"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Color: {self.rgba}"
|
||||
|
||||
|
||||
# Basic, extended and transparent colour keywords as defined by the W3C HTML4 spec
|
||||
# See http://www.w3.org/TR/css3-color/#html4
|
||||
Colors = {
|
||||
"TRANSPARENT": Color(0, 0, 0, 0),
|
||||
"ALICEBLUE": Color(240, 248, 255),
|
||||
"ANTIQUEWHITE": Color(250, 235, 215),
|
||||
"AQUA": Color(0, 255, 255),
|
||||
"AQUAMARINE": Color(127, 255, 212),
|
||||
"AZURE": Color(240, 255, 255),
|
||||
"BEIGE": Color(245, 245, 220),
|
||||
"BISQUE": Color(255, 228, 196),
|
||||
"BLACK": Color(0, 0, 0),
|
||||
"BLANCHEDALMOND": Color(255, 235, 205),
|
||||
"BLUE": Color(0, 0, 255),
|
||||
"BLUEVIOLET": Color(138, 43, 226),
|
||||
"BROWN": Color(165, 42, 42),
|
||||
"BURLYWOOD": Color(222, 184, 135),
|
||||
"CADETBLUE": Color(95, 158, 160),
|
||||
"CHARTREUSE": Color(127, 255, 0),
|
||||
"CHOCOLATE": Color(210, 105, 30),
|
||||
"CORAL": Color(255, 127, 80),
|
||||
"CORNFLOWERBLUE": Color(100, 149, 237),
|
||||
"CORNSILK": Color(255, 248, 220),
|
||||
"CRIMSON": Color(220, 20, 60),
|
||||
"CYAN": Color(0, 255, 255),
|
||||
"DARKBLUE": Color(0, 0, 139),
|
||||
"DARKCYAN": Color(0, 139, 139),
|
||||
"DARKGOLDENROD": Color(184, 134, 11),
|
||||
"DARKGRAY": Color(169, 169, 169),
|
||||
"DARKGREEN": Color(0, 100, 0),
|
||||
"DARKGREY": Color(169, 169, 169),
|
||||
"DARKKHAKI": Color(189, 183, 107),
|
||||
"DARKMAGENTA": Color(139, 0, 139),
|
||||
"DARKOLIVEGREEN": Color(85, 107, 47),
|
||||
"DARKORANGE": Color(255, 140, 0),
|
||||
"DARKORCHID": Color(153, 50, 204),
|
||||
"DARKRED": Color(139, 0, 0),
|
||||
"DARKSALMON": Color(233, 150, 122),
|
||||
"DARKSEAGREEN": Color(143, 188, 143),
|
||||
"DARKSLATEBLUE": Color(72, 61, 139),
|
||||
"DARKSLATEGRAY": Color(47, 79, 79),
|
||||
"DARKSLATEGREY": Color(47, 79, 79),
|
||||
"DARKTURQUOISE": Color(0, 206, 209),
|
||||
"DARKVIOLET": Color(148, 0, 211),
|
||||
"DEEPPINK": Color(255, 20, 147),
|
||||
"DEEPSKYBLUE": Color(0, 191, 255),
|
||||
"DIMGRAY": Color(105, 105, 105),
|
||||
"DIMGREY": Color(105, 105, 105),
|
||||
"DODGERBLUE": Color(30, 144, 255),
|
||||
"FIREBRICK": Color(178, 34, 34),
|
||||
"FLORALWHITE": Color(255, 250, 240),
|
||||
"FORESTGREEN": Color(34, 139, 34),
|
||||
"FUCHSIA": Color(255, 0, 255),
|
||||
"GAINSBORO": Color(220, 220, 220),
|
||||
"GHOSTWHITE": Color(248, 248, 255),
|
||||
"GOLD": Color(255, 215, 0),
|
||||
"GOLDENROD": Color(218, 165, 32),
|
||||
"GRAY": Color(128, 128, 128),
|
||||
"GREY": Color(128, 128, 128),
|
||||
"GREEN": Color(0, 128, 0),
|
||||
"GREENYELLOW": Color(173, 255, 47),
|
||||
"HONEYDEW": Color(240, 255, 240),
|
||||
"HOTPINK": Color(255, 105, 180),
|
||||
"INDIANRED": Color(205, 92, 92),
|
||||
"INDIGO": Color(75, 0, 130),
|
||||
"IVORY": Color(255, 255, 240),
|
||||
"KHAKI": Color(240, 230, 140),
|
||||
"LAVENDER": Color(230, 230, 250),
|
||||
"LAVENDERBLUSH": Color(255, 240, 245),
|
||||
"LAWNGREEN": Color(124, 252, 0),
|
||||
"LEMONCHIFFON": Color(255, 250, 205),
|
||||
"LIGHTBLUE": Color(173, 216, 230),
|
||||
"LIGHTCORAL": Color(240, 128, 128),
|
||||
"LIGHTCYAN": Color(224, 255, 255),
|
||||
"LIGHTGOLDENRODYELLOW": Color(250, 250, 210),
|
||||
"LIGHTGRAY": Color(211, 211, 211),
|
||||
"LIGHTGREEN": Color(144, 238, 144),
|
||||
"LIGHTGREY": Color(211, 211, 211),
|
||||
"LIGHTPINK": Color(255, 182, 193),
|
||||
"LIGHTSALMON": Color(255, 160, 122),
|
||||
"LIGHTSEAGREEN": Color(32, 178, 170),
|
||||
"LIGHTSKYBLUE": Color(135, 206, 250),
|
||||
"LIGHTSLATEGRAY": Color(119, 136, 153),
|
||||
"LIGHTSLATEGREY": Color(119, 136, 153),
|
||||
"LIGHTSTEELBLUE": Color(176, 196, 222),
|
||||
"LIGHTYELLOW": Color(255, 255, 224),
|
||||
"LIME": Color(0, 255, 0),
|
||||
"LIMEGREEN": Color(50, 205, 50),
|
||||
"LINEN": Color(250, 240, 230),
|
||||
"MAGENTA": Color(255, 0, 255),
|
||||
"MAROON": Color(128, 0, 0),
|
||||
"MEDIUMAQUAMARINE": Color(102, 205, 170),
|
||||
"MEDIUMBLUE": Color(0, 0, 205),
|
||||
"MEDIUMORCHID": Color(186, 85, 211),
|
||||
"MEDIUMPURPLE": Color(147, 112, 219),
|
||||
"MEDIUMSEAGREEN": Color(60, 179, 113),
|
||||
"MEDIUMSLATEBLUE": Color(123, 104, 238),
|
||||
"MEDIUMSPRINGGREEN": Color(0, 250, 154),
|
||||
"MEDIUMTURQUOISE": Color(72, 209, 204),
|
||||
"MEDIUMVIOLETRED": Color(199, 21, 133),
|
||||
"MIDNIGHTBLUE": Color(25, 25, 112),
|
||||
"MINTCREAM": Color(245, 255, 250),
|
||||
"MISTYROSE": Color(255, 228, 225),
|
||||
"MOCCASIN": Color(255, 228, 181),
|
||||
"NAVAJOWHITE": Color(255, 222, 173),
|
||||
"NAVY": Color(0, 0, 128),
|
||||
"OLDLACE": Color(253, 245, 230),
|
||||
"OLIVE": Color(128, 128, 0),
|
||||
"OLIVEDRAB": Color(107, 142, 35),
|
||||
"ORANGE": Color(255, 165, 0),
|
||||
"ORANGERED": Color(255, 69, 0),
|
||||
"ORCHID": Color(218, 112, 214),
|
||||
"PALEGOLDENROD": Color(238, 232, 170),
|
||||
"PALEGREEN": Color(152, 251, 152),
|
||||
"PALETURQUOISE": Color(175, 238, 238),
|
||||
"PALEVIOLETRED": Color(219, 112, 147),
|
||||
"PAPAYAWHIP": Color(255, 239, 213),
|
||||
"PEACHPUFF": Color(255, 218, 185),
|
||||
"PERU": Color(205, 133, 63),
|
||||
"PINK": Color(255, 192, 203),
|
||||
"PLUM": Color(221, 160, 221),
|
||||
"POWDERBLUE": Color(176, 224, 230),
|
||||
"PURPLE": Color(128, 0, 128),
|
||||
"REBECCAPURPLE": Color(128, 51, 153),
|
||||
"RED": Color(255, 0, 0),
|
||||
"ROSYBROWN": Color(188, 143, 143),
|
||||
"ROYALBLUE": Color(65, 105, 225),
|
||||
"SADDLEBROWN": Color(139, 69, 19),
|
||||
"SALMON": Color(250, 128, 114),
|
||||
"SANDYBROWN": Color(244, 164, 96),
|
||||
"SEAGREEN": Color(46, 139, 87),
|
||||
"SEASHELL": Color(255, 245, 238),
|
||||
"SIENNA": Color(160, 82, 45),
|
||||
"SILVER": Color(192, 192, 192),
|
||||
"SKYBLUE": Color(135, 206, 235),
|
||||
"SLATEBLUE": Color(106, 90, 205),
|
||||
"SLATEGRAY": Color(112, 128, 144),
|
||||
"SLATEGREY": Color(112, 128, 144),
|
||||
"SNOW": Color(255, 250, 250),
|
||||
"SPRINGGREEN": Color(0, 255, 127),
|
||||
"STEELBLUE": Color(70, 130, 180),
|
||||
"TAN": Color(210, 180, 140),
|
||||
"TEAL": Color(0, 128, 128),
|
||||
"THISTLE": Color(216, 191, 216),
|
||||
"TOMATO": Color(255, 99, 71),
|
||||
"TURQUOISE": Color(64, 224, 208),
|
||||
"VIOLET": Color(238, 130, 238),
|
||||
"WHEAT": Color(245, 222, 179),
|
||||
"WHITE": Color(255, 255, 255),
|
||||
"WHITESMOKE": Color(245, 245, 245),
|
||||
"YELLOW": Color(255, 255, 0),
|
||||
"YELLOWGREEN": Color(154, 205, 50),
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.remote.webdriver import WebDriver
|
||||
from selenium.webdriver.remote.webelement import WebElement
|
||||
from selenium.webdriver.support.abstract_event_listener import AbstractEventListener
|
||||
|
||||
|
||||
def _wrap_elements(result, ef_driver):
|
||||
# handle the case if another wrapper wraps EventFiringWebElement
|
||||
if isinstance(result, EventFiringWebElement):
|
||||
return result
|
||||
if isinstance(result, WebElement):
|
||||
return EventFiringWebElement(result, ef_driver)
|
||||
if isinstance(result, list):
|
||||
return [_wrap_elements(item, ef_driver) for item in result]
|
||||
return result
|
||||
|
||||
|
||||
class EventFiringWebDriver:
|
||||
"""Wrap an arbitrary WebDriver instance and support firing events.
|
||||
|
||||
This wrapper allows you to hook into various WebDriver events through an
|
||||
AbstractEventListener implementation.
|
||||
"""
|
||||
|
||||
def __init__(self, driver: WebDriver, event_listener: AbstractEventListener) -> None:
|
||||
"""Creates a new instance of the EventFiringWebDriver.
|
||||
|
||||
Args:
|
||||
driver: A WebDriver instance
|
||||
event_listener: Instance of a class that subclasses AbstractEventListener and implements it fully
|
||||
or partially
|
||||
|
||||
Example:
|
||||
from selenium.webdriver import Firefox
|
||||
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener
|
||||
|
||||
|
||||
class MyListener(AbstractEventListener):
|
||||
def before_navigate_to(self, url, driver):
|
||||
print("Before navigate to %s" % url)
|
||||
|
||||
def after_navigate_to(self, url, driver):
|
||||
print("After navigate to %s" % url)
|
||||
|
||||
|
||||
driver = Firefox()
|
||||
ef_driver = EventFiringWebDriver(driver, MyListener())
|
||||
ef_driver.get("http://www.google.co.in/")
|
||||
"""
|
||||
if not isinstance(driver, WebDriver):
|
||||
raise WebDriverException("A WebDriver instance must be supplied")
|
||||
if not isinstance(event_listener, AbstractEventListener):
|
||||
raise WebDriverException("Event listener must be a subclass of AbstractEventListener")
|
||||
self._driver = driver
|
||||
# this is valid, but type checkers don't like dynamically assigning to a method
|
||||
self._driver._wrap_value = self._wrap_value # type: ignore
|
||||
self._listener = event_listener
|
||||
|
||||
@property
|
||||
def wrapped_driver(self) -> WebDriver:
|
||||
"""Returns the WebDriver instance wrapped by this EventsFiringWebDriver."""
|
||||
return self._driver
|
||||
|
||||
def get(self, url: str) -> None:
|
||||
self._dispatch("navigate_to", (url, self._driver), "get", (url,))
|
||||
|
||||
def back(self) -> None:
|
||||
self._dispatch("navigate_back", (self._driver,), "back", ())
|
||||
|
||||
def forward(self) -> None:
|
||||
self._dispatch("navigate_forward", (self._driver,), "forward", ())
|
||||
|
||||
def execute_script(self, script: str, *args):
|
||||
unwrapped_args = (script,) + self._unwrap_element_args(args)
|
||||
return self._dispatch("execute_script", (script, self._driver), "execute_script", unwrapped_args)
|
||||
|
||||
def execute_async_script(self, script, *args):
|
||||
unwrapped_args = (script,) + self._unwrap_element_args(args)
|
||||
return self._dispatch("execute_script", (script, self._driver), "execute_async_script", unwrapped_args)
|
||||
|
||||
def close(self) -> None:
|
||||
self._dispatch("close", (self._driver,), "close", ())
|
||||
|
||||
def quit(self) -> None:
|
||||
self._dispatch("quit", (self._driver,), "quit", ())
|
||||
|
||||
def find_element(self, by=By.ID, value=None) -> WebElement:
|
||||
return self._dispatch("find", (by, value, self._driver), "find_element", (by, value))
|
||||
|
||||
def find_elements(self, by=By.ID, value=None) -> list[WebElement]:
|
||||
return self._dispatch("find", (by, value, self._driver), "find_elements", (by, value))
|
||||
|
||||
def _dispatch(self, l_call: str, l_args: tuple[Any, ...], d_call: str, d_args: tuple[Any, ...]):
|
||||
getattr(self._listener, f"before_{l_call}")(*l_args)
|
||||
try:
|
||||
result = getattr(self._driver, d_call)(*d_args)
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
getattr(self._listener, f"after_{l_call}")(*l_args)
|
||||
return _wrap_elements(result, self)
|
||||
|
||||
def _unwrap_element_args(self, args):
|
||||
if isinstance(args, EventFiringWebElement):
|
||||
return args.wrapped_element
|
||||
if isinstance(args, tuple):
|
||||
return tuple(self._unwrap_element_args(item) for item in args)
|
||||
if isinstance(args, list):
|
||||
return [self._unwrap_element_args(item) for item in args]
|
||||
return args
|
||||
|
||||
def _wrap_value(self, value):
|
||||
if isinstance(value, EventFiringWebElement):
|
||||
return WebDriver._wrap_value(self._driver, value.wrapped_element)
|
||||
return WebDriver._wrap_value(self._driver, value)
|
||||
|
||||
def __setattr__(self, item, value):
|
||||
if item.startswith("_") or not hasattr(self._driver, item):
|
||||
object.__setattr__(self, item, value)
|
||||
else:
|
||||
try:
|
||||
object.__setattr__(self._driver, item, value)
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
|
||||
def __getattr__(self, name):
|
||||
def _wrap(*args, **kwargs):
|
||||
try:
|
||||
result = attrib(*args, **kwargs)
|
||||
return _wrap_elements(result, self)
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
|
||||
try:
|
||||
attrib = getattr(self._driver, name)
|
||||
return _wrap if callable(attrib) else attrib
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
|
||||
|
||||
class EventFiringWebElement:
|
||||
"""A wrapper around WebElement instance which supports firing events."""
|
||||
|
||||
def __init__(self, webelement: WebElement, ef_driver: EventFiringWebDriver) -> None:
|
||||
"""Creates a new instance of the EventFiringWebElement."""
|
||||
self._webelement = webelement
|
||||
self._ef_driver = ef_driver
|
||||
self._driver = ef_driver.wrapped_driver
|
||||
self._listener = ef_driver._listener
|
||||
|
||||
@property
|
||||
def wrapped_element(self) -> WebElement:
|
||||
"""Returns the WebElement wrapped by this EventFiringWebElement instance."""
|
||||
return self._webelement
|
||||
|
||||
def click(self) -> None:
|
||||
self._dispatch("click", (self._webelement, self._driver), "click", ())
|
||||
|
||||
def clear(self) -> None:
|
||||
self._dispatch("change_value_of", (self._webelement, self._driver), "clear", ())
|
||||
|
||||
def send_keys(self, *value) -> None:
|
||||
self._dispatch("change_value_of", (self._webelement, self._driver), "send_keys", value)
|
||||
|
||||
def find_element(self, by=By.ID, value=None) -> WebElement:
|
||||
return self._dispatch("find", (by, value, self._driver), "find_element", (by, value))
|
||||
|
||||
def find_elements(self, by=By.ID, value=None) -> list[WebElement]:
|
||||
return self._dispatch("find", (by, value, self._driver), "find_elements", (by, value))
|
||||
|
||||
def _dispatch(self, l_call, l_args, d_call, d_args):
|
||||
getattr(self._listener, f"before_{l_call}")(*l_args)
|
||||
try:
|
||||
result = getattr(self._webelement, d_call)(*d_args)
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
getattr(self._listener, f"after_{l_call}")(*l_args)
|
||||
return _wrap_elements(result, self._ef_driver)
|
||||
|
||||
def __setattr__(self, item, value):
|
||||
if item.startswith("_") or not hasattr(self._webelement, item):
|
||||
object.__setattr__(self, item, value)
|
||||
else:
|
||||
try:
|
||||
object.__setattr__(self._webelement, item, value)
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
|
||||
def __getattr__(self, name):
|
||||
def _wrap(*args, **kwargs):
|
||||
try:
|
||||
result = attrib(*args, **kwargs)
|
||||
return _wrap_elements(result, self._ef_driver)
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
|
||||
try:
|
||||
attrib = getattr(self._webelement, name)
|
||||
return _wrap if callable(attrib) else attrib
|
||||
except Exception as exc:
|
||||
self._listener.on_exception(exc, self._driver)
|
||||
raise
|
||||
|
||||
|
||||
# Register a virtual subclass.
|
||||
WebElement.register(EventFiringWebElement)
|
||||
@@ -0,0 +1,19 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from selenium.webdriver.support.abstract_event_listener import AbstractEventListener # noqa
|
||||
from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver # noqa
|
||||
+851
@@ -0,0 +1,851 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import re
|
||||
from collections.abc import Callable, Iterable
|
||||
from typing import Any, Literal, TypeVar
|
||||
|
||||
from selenium.common.exceptions import (
|
||||
NoAlertPresentException,
|
||||
NoSuchElementException,
|
||||
NoSuchFrameException,
|
||||
StaleElementReferenceException,
|
||||
WebDriverException,
|
||||
)
|
||||
from selenium.webdriver.common.alert import Alert
|
||||
from selenium.webdriver.remote.webdriver import WebDriver, WebElement
|
||||
|
||||
"""
|
||||
* Canned "Expected Conditions" which are generally useful within webdriver
|
||||
* tests.
|
||||
"""
|
||||
|
||||
D = TypeVar("D")
|
||||
T = TypeVar("T")
|
||||
|
||||
WebDriverOrWebElement = WebDriver | WebElement
|
||||
|
||||
|
||||
def title_is(title: str) -> Callable[[WebDriver], bool]:
|
||||
"""An expectation for checking the title of a page.
|
||||
|
||||
Args:
|
||||
title: The expected title, which must be an exact match.
|
||||
|
||||
Returns:
|
||||
True if the title matches, False otherwise.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return driver.title == title
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def title_contains(title: str) -> Callable[[WebDriver], bool]:
|
||||
"""Check that the title contains a case-sensitive substring.
|
||||
|
||||
Args:
|
||||
title: The fragment of title expected.
|
||||
|
||||
Returns:
|
||||
True when the title matches, False otherwise.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return title in driver.title
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def presence_of_element_located(locator: tuple[str, str]) -> Callable[[WebDriverOrWebElement], WebElement]:
|
||||
"""Check that an element is present on the DOM (not necessarily visible).
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
|
||||
Returns:
|
||||
The WebElement once it is located.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "q")))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
return driver.find_element(*locator)
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def url_contains(url: str) -> Callable[[WebDriver], bool]:
|
||||
"""Check that the current url contains a case-sensitive substring.
|
||||
|
||||
Args:
|
||||
url: The fragment of url expected.
|
||||
|
||||
Returns:
|
||||
True when the url matches, False otherwise.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return url in driver.current_url
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def url_matches(pattern: str) -> Callable[[WebDriver], bool]:
|
||||
"""An expectation for checking the current url.
|
||||
|
||||
Args:
|
||||
pattern: The pattern to match with the current url.
|
||||
|
||||
Returns:
|
||||
True when the pattern matches, False otherwise.
|
||||
|
||||
Note:
|
||||
More powerful than url_contains, as it allows for regular expressions.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return re.search(pattern, driver.current_url) is not None
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def url_to_be(url: str) -> Callable[[WebDriver], bool]:
|
||||
"""An expectation for checking the current url.
|
||||
|
||||
Args:
|
||||
url: The expected url, which must be an exact match.
|
||||
|
||||
Returns:
|
||||
True when the url matches, False otherwise.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return url == driver.current_url
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def url_changes(url: str) -> Callable[[WebDriver], bool]:
|
||||
"""Check that the current url differs from a given string.
|
||||
|
||||
Args:
|
||||
url: The expected url, which must not be an exact match.
|
||||
|
||||
Returns:
|
||||
True when the url does not match, False otherwise.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return url != driver.current_url
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def visibility_of_element_located(
|
||||
locator: tuple[str, str],
|
||||
) -> Callable[[WebDriverOrWebElement], Literal[False] | WebElement]:
|
||||
"""Check that an element is visible (present in DOM and width/height greater than zero).
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
|
||||
Returns:
|
||||
The WebElement once it is located and visible.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, "q")))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
return _element_if_visible(driver.find_element(*locator))
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def visibility_of(element: WebElement) -> Callable[[Any], Literal[False] | WebElement]:
|
||||
"""Check that an element is visible (present in DOM and width/height greater than zero).
|
||||
|
||||
Args:
|
||||
element: The WebElement to check.
|
||||
|
||||
Returns:
|
||||
The WebElement once it is visible.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
element = WebDriverWait(driver, 10).until(EC.visibility_of(driver.find_element(By.NAME, "q")))
|
||||
"""
|
||||
|
||||
def _predicate(_):
|
||||
return _element_if_visible(element)
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def _element_if_visible(element: WebElement, visibility: bool = True) -> Literal[False] | WebElement:
|
||||
"""Check if an element has the expected visibility state.
|
||||
|
||||
Args:
|
||||
element: The WebElement to check.
|
||||
visibility: The expected visibility of the element.
|
||||
|
||||
Returns:
|
||||
The WebElement once it is visible or not visible.
|
||||
"""
|
||||
return element if element.is_displayed() == visibility else False
|
||||
|
||||
|
||||
def presence_of_all_elements_located(locator: tuple[str, str]) -> Callable[[WebDriverOrWebElement], list[WebElement]]:
|
||||
"""Check that all elements matching the locator are present on the DOM.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
|
||||
Returns:
|
||||
The list of WebElements once they are located.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "foo")))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
return driver.find_elements(*locator)
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def visibility_of_any_elements_located(locator: tuple[str, str]) -> Callable[[WebDriverOrWebElement], list[WebElement]]:
|
||||
"""Check that at least one element is visible on the web page (present in DOM and width/height greater than zero).
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
|
||||
Returns:
|
||||
The list of WebElements once they are located and visible.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
elements = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "foo")))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
return [element for element in driver.find_elements(*locator) if _element_if_visible(element)]
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def visibility_of_all_elements_located(
|
||||
locator: tuple[str, str],
|
||||
) -> Callable[[WebDriverOrWebElement], list[WebElement] | Literal[False]]:
|
||||
"""Check that all elements are visible (present in DOM and width/height greater than zero).
|
||||
|
||||
Args:
|
||||
locator: Used to find the elements.
|
||||
|
||||
Returns:
|
||||
The list of WebElements once they are located and visible.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
elements = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "foo")))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
elements = driver.find_elements(*locator)
|
||||
for element in elements:
|
||||
if _element_if_visible(element, visibility=False):
|
||||
return False
|
||||
return elements
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def text_to_be_present_in_element(locator: tuple[str, str], text_: str) -> Callable[[WebDriverOrWebElement], bool]:
|
||||
"""Check that the given text is present in the specified element.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
text_: The text to be present in the element.
|
||||
|
||||
Returns:
|
||||
True when the text is present, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_text_in_element = WebDriverWait(driver, 10).until(
|
||||
EC.text_to_be_present_in_element((By.CLASS_NAME, "foo"), "bar")
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
element_text = driver.find_element(*locator).text
|
||||
return text_ in element_text
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def text_to_be_present_in_element_value(
|
||||
locator: tuple[str, str], text_: str
|
||||
) -> Callable[[WebDriverOrWebElement], bool]:
|
||||
"""Check that the given text is present in the element's value.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
text_: The text to be present in the element's value.
|
||||
|
||||
Returns:
|
||||
True when the text is present, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_text_in_element_value = WebDriverWait(driver, 10).until(
|
||||
EC.text_to_be_present_in_element_value((By.CLASS_NAME, "foo"), "bar")
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
element_text = driver.find_element(*locator).get_attribute("value")
|
||||
if element_text is None:
|
||||
return False
|
||||
return text_ in element_text
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def text_to_be_present_in_element_attribute(
|
||||
locator: tuple[str, str], attribute_: str, text_: str
|
||||
) -> Callable[[WebDriverOrWebElement], bool]:
|
||||
"""Check that the given text is present in the element's attribute.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
attribute_: The attribute to check the text in.
|
||||
text_: The text to be present in the element's attribute.
|
||||
|
||||
Returns:
|
||||
True when the text is present, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_text_in_element_attribute = WebDriverWait(driver, 10).until(
|
||||
EC.text_to_be_present_in_element_attribute((By.CLASS_NAME, "foo"), "bar", "baz")
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
element_text = driver.find_element(*locator).get_attribute(attribute_)
|
||||
if element_text is None:
|
||||
return False
|
||||
return text_ in element_text
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def frame_to_be_available_and_switch_to_it(
|
||||
locator: tuple[str, str] | str | WebElement,
|
||||
) -> Callable[[WebDriver], bool]:
|
||||
"""Check that the given frame is available and switch to it.
|
||||
|
||||
Args:
|
||||
locator: Used to find the frame.
|
||||
|
||||
Returns:
|
||||
True when the frame is available, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("frame_name"))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
try:
|
||||
if isinstance(locator, Iterable) and not isinstance(locator, str):
|
||||
driver.switch_to.frame(driver.find_element(*locator))
|
||||
else:
|
||||
driver.switch_to.frame(locator)
|
||||
return True
|
||||
except NoSuchFrameException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def invisibility_of_element_located(
|
||||
locator: WebElement | tuple[str, str],
|
||||
) -> Callable[[WebDriverOrWebElement], WebElement | bool]:
|
||||
"""Check that an element is either invisible or not present on the DOM.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
|
||||
Returns:
|
||||
True when the element is invisible or not present, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_invisible = WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((By.CLASS_NAME, "foo")))
|
||||
|
||||
Note:
|
||||
In the case of NoSuchElement, returns true because the element is not
|
||||
present in DOM. The try block checks if the element is present but is
|
||||
invisible.
|
||||
In the case of StaleElementReference, returns true because stale element
|
||||
reference implies that element is no longer visible.
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
target = locator
|
||||
if not isinstance(target, WebElement):
|
||||
target = driver.find_element(*target)
|
||||
return _element_if_visible(target, visibility=False)
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
# In the case of NoSuchElement, returns true because the element is
|
||||
# not present in DOM. The try block checks if the element is present
|
||||
# but is invisible.
|
||||
# In the case of StaleElementReference, returns true because stale
|
||||
# element reference implies that element is no longer visible.
|
||||
return True
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def invisibility_of_element(
|
||||
element: WebElement | tuple[str, str],
|
||||
) -> Callable[[WebDriverOrWebElement], WebElement | bool]:
|
||||
"""Check that an element is either invisible or not present on the DOM.
|
||||
|
||||
Args:
|
||||
element: Used to find the element.
|
||||
|
||||
Returns:
|
||||
True when the element is invisible or not present, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_invisible_or_not_present = WebDriverWait(driver, 10).until(
|
||||
EC.invisibility_of_element(driver.find_element(By.CLASS_NAME, "foo"))
|
||||
)
|
||||
"""
|
||||
return invisibility_of_element_located(element)
|
||||
|
||||
|
||||
def element_to_be_clickable(
|
||||
mark: WebElement | tuple[str, str],
|
||||
) -> Callable[[WebDriverOrWebElement], Literal[False] | WebElement]:
|
||||
"""Check that an element is visible and enabled so it can be clicked.
|
||||
|
||||
Args:
|
||||
mark: Used to find the element.
|
||||
|
||||
Returns:
|
||||
The WebElement once it is located and clickable.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "foo")))
|
||||
"""
|
||||
|
||||
# renamed argument to 'mark', to indicate that both locator
|
||||
# and WebElement args are valid
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
target = mark
|
||||
if not isinstance(target, WebElement): # if given locator instead of WebElement
|
||||
target = driver.find_element(*target) # grab element at locator
|
||||
element = visibility_of(target)(driver)
|
||||
if element and element.is_enabled():
|
||||
return element
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def staleness_of(element: WebElement) -> Callable[[Any], bool]:
|
||||
"""Wait until an element is no longer attached to the DOM.
|
||||
|
||||
Args:
|
||||
element: The element to wait for.
|
||||
|
||||
Returns:
|
||||
False if the element is still attached to the DOM, true otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_stale = WebDriverWait(driver, 10).until(EC.staleness_of(driver.find_element(By.CLASS_NAME, "foo")))
|
||||
"""
|
||||
|
||||
def _predicate(_):
|
||||
try:
|
||||
# Calling any method forces a staleness check
|
||||
element.is_enabled()
|
||||
return False
|
||||
except StaleElementReferenceException:
|
||||
return True
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def element_to_be_selected(element: WebElement) -> Callable[[Any], bool]:
|
||||
"""An expectation for checking the selection is selected.
|
||||
|
||||
Args:
|
||||
element: The WebElement to check.
|
||||
|
||||
Returns:
|
||||
True if the element is selected, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_selected = WebDriverWait(driver, 10).until(EC.element_to_be_selected(driver.find_element(
|
||||
By.CLASS_NAME, "foo"))
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(_):
|
||||
return element.is_selected()
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def element_located_to_be_selected(locator: tuple[str, str]) -> Callable[[WebDriverOrWebElement], bool]:
|
||||
"""An expectation for the element to be located is selected.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
|
||||
Returns:
|
||||
True if the element is selected, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_selected = WebDriverWait(driver, 10).until(EC.element_located_to_be_selected((By.CLASS_NAME, "foo")))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
return driver.find_element(*locator).is_selected()
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def element_selection_state_to_be(element: WebElement, is_selected: bool) -> Callable[[Any], bool]:
|
||||
"""An expectation for checking if the given element is selected.
|
||||
|
||||
Args:
|
||||
element: The WebElement to check.
|
||||
is_selected: The expected selection state.
|
||||
|
||||
Returns:
|
||||
True if the element's selection state is the same as is_selected.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_selected = WebDriverWait(driver, 10).until(
|
||||
EC.element_selection_state_to_be(driver.find_element(By.CLASS_NAME, "foo"), True)
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(_):
|
||||
return element.is_selected() == is_selected
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def element_located_selection_state_to_be(
|
||||
locator: tuple[str, str], is_selected: bool
|
||||
) -> Callable[[WebDriverOrWebElement], bool]:
|
||||
"""Check that an element's selection state matches the expected state.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
is_selected: The expected selection state.
|
||||
|
||||
Returns:
|
||||
True if the element's selection state is the same as is_selected.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_selected = WebDriverWait(driver, 10).until(EC.element_located_selection_state_to_be(
|
||||
(By.CLASS_NAME, "foo"), True)
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
element = driver.find_element(*locator)
|
||||
return element.is_selected() == is_selected
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def number_of_windows_to_be(num_windows: int) -> Callable[[WebDriver], bool]:
|
||||
"""An expectation for the number of windows to be a certain value.
|
||||
|
||||
Args:
|
||||
num_windows: The expected number of windows.
|
||||
|
||||
Returns:
|
||||
True when the number of windows matches, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_number_of_windows = WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return len(driver.window_handles) == num_windows
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def new_window_is_opened(current_handles: set[str]) -> Callable[[WebDriver], bool]:
|
||||
"""Check that a new window has been opened (window handles count increased).
|
||||
|
||||
Args:
|
||||
current_handles: The current window handles.
|
||||
|
||||
Returns:
|
||||
True when a new window is opened, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.support.ui import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_new_window_opened = WebDriverWait(driver, 10).until(EC.new_window_is_opened(driver.window_handles))
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
return len(driver.window_handles) > len(current_handles)
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def alert_is_present() -> Callable[[WebDriver], Alert | Literal[False]]:
|
||||
"""Check that an alert is present and switch to it.
|
||||
|
||||
Returns:
|
||||
The Alert once it is located, or False if no alert is present.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
alert = WebDriverWait(driver, 10).until(EC.alert_is_present())
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriver):
|
||||
try:
|
||||
return driver.switch_to.alert
|
||||
except NoAlertPresentException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def element_attribute_to_include(locator: tuple[str, str], attribute_: str) -> Callable[[WebDriverOrWebElement], bool]:
|
||||
"""Check if the given attribute is included in the specified element.
|
||||
|
||||
Args:
|
||||
locator: Used to find the element.
|
||||
attribute_: The attribute to check.
|
||||
|
||||
Returns:
|
||||
True when the attribute is included, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
is_attribute_in_element = WebDriverWait(driver, 10).until(
|
||||
EC.element_attribute_to_include((By.CLASS_NAME, "foo"), "bar")
|
||||
)
|
||||
"""
|
||||
|
||||
def _predicate(driver: WebDriverOrWebElement):
|
||||
try:
|
||||
element_attribute = driver.find_element(*locator).get_attribute(attribute_)
|
||||
return element_attribute is not None
|
||||
except StaleElementReferenceException:
|
||||
return False
|
||||
|
||||
return _predicate
|
||||
|
||||
|
||||
def any_of(*expected_conditions: Callable[[D], T]) -> Callable[[D], Literal[False] | T]:
|
||||
"""An expectation that any of multiple expected conditions is true.
|
||||
|
||||
Equivalent to a logical 'OR'. Returns results of the first matching
|
||||
condition, or False if none do.
|
||||
|
||||
Args:
|
||||
expected_conditions: The list of expected conditions to check.
|
||||
|
||||
Returns:
|
||||
The result of the first matching condition, or False if none do.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
element = WebDriverWait(driver, 10).until(
|
||||
EC.any_of(EC.presence_of_element_located((By.NAME, "q"),
|
||||
EC.visibility_of_element_located((By.NAME, "q")))
|
||||
)
|
||||
"""
|
||||
|
||||
def any_of_condition(driver: D):
|
||||
for expected_condition in expected_conditions:
|
||||
try:
|
||||
result = expected_condition(driver)
|
||||
if result:
|
||||
return result
|
||||
except WebDriverException:
|
||||
pass
|
||||
return False
|
||||
|
||||
return any_of_condition
|
||||
|
||||
|
||||
def all_of(
|
||||
*expected_conditions: Callable[[D], T | Literal[False]],
|
||||
) -> Callable[[D], list[T] | Literal[False]]:
|
||||
"""An expectation that all of multiple expected conditions is true.
|
||||
|
||||
Equivalent to a logical 'AND'. When any ExpectedCondition is not met,
|
||||
returns False. When all ExpectedConditions are met, returns a List with
|
||||
each ExpectedCondition's return value.
|
||||
|
||||
Args:
|
||||
expected_conditions: The list of expected conditions to check.
|
||||
|
||||
Returns:
|
||||
The results of all the matching conditions, or False if any do not.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
elements = WebDriverWait(driver, 10).until(
|
||||
EC.all_of(EC.presence_of_element_located((By.NAME, "q"),
|
||||
EC.visibility_of_element_located((By.NAME, "q")))
|
||||
)
|
||||
"""
|
||||
|
||||
def all_of_condition(driver: D):
|
||||
results: list[T] = []
|
||||
for expected_condition in expected_conditions:
|
||||
try:
|
||||
result = expected_condition(driver)
|
||||
if not result:
|
||||
return False
|
||||
results.append(result)
|
||||
except WebDriverException:
|
||||
return False
|
||||
return results
|
||||
|
||||
return all_of_condition
|
||||
|
||||
|
||||
def none_of(*expected_conditions: Callable[[D], Any]) -> Callable[[D], bool]:
|
||||
"""An expectation that none of 1 or multiple expected conditions is true.
|
||||
|
||||
Equivalent to a logical 'NOT-OR'.
|
||||
|
||||
Args:
|
||||
expected_conditions: The list of expected conditions to check.
|
||||
|
||||
Returns:
|
||||
True if none of the conditions are true, False otherwise.
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
element = WebDriverWait(driver, 10).until(
|
||||
EC.none_of(EC.presence_of_element_located((By.NAME, "q"),
|
||||
EC.visibility_of_element_located((By.NAME, "q")))
|
||||
)
|
||||
"""
|
||||
|
||||
def none_of_condition(driver: D):
|
||||
for expected_condition in expected_conditions:
|
||||
try:
|
||||
result = expected_condition(driver)
|
||||
if result:
|
||||
return False
|
||||
except WebDriverException:
|
||||
pass
|
||||
return True
|
||||
|
||||
return none_of_condition
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
import warnings
|
||||
from typing import NoReturn, overload
|
||||
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.webdriver.common.by import By, ByType
|
||||
from selenium.webdriver.remote.webelement import WebElement
|
||||
|
||||
|
||||
def with_tag_name(tag_name: str) -> "RelativeBy":
|
||||
"""Start searching for relative objects using a tag name.
|
||||
|
||||
Args:
|
||||
tag_name: The DOM tag of element to start searching.
|
||||
|
||||
Returns:
|
||||
RelativeBy: Use this object to create filters within a `find_elements` call.
|
||||
|
||||
Raises:
|
||||
WebDriverException: If `tag_name` is None.
|
||||
|
||||
Note:
|
||||
This method is deprecated and may be removed in future versions.
|
||||
Please use `locate_with` instead.
|
||||
"""
|
||||
warnings.warn("This method is deprecated and may be removed in future versions. Please use `locate_with` instead.")
|
||||
if not tag_name:
|
||||
raise WebDriverException("tag_name can not be null")
|
||||
return RelativeBy({By.CSS_SELECTOR: tag_name})
|
||||
|
||||
|
||||
def locate_with(by: ByType, using: str) -> "RelativeBy":
|
||||
"""Start searching for relative objects your search criteria with By.
|
||||
|
||||
Args:
|
||||
by: The method to find the element.
|
||||
using: The value from `By` passed in.
|
||||
|
||||
Returns:
|
||||
RelativeBy: Use this object to create filters within a `find_elements` call.
|
||||
|
||||
Example:
|
||||
>>> lowest = driver.find_element(By.ID, "below")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").above(lowest))
|
||||
"""
|
||||
assert by is not None, "Please pass in a by argument"
|
||||
assert using is not None, "Please pass in a using argument"
|
||||
return RelativeBy({by: using})
|
||||
|
||||
|
||||
class RelativeBy:
|
||||
"""Find elements based on their relative location from a root element.
|
||||
|
||||
It is recommended that you use the helper function to create instances.
|
||||
|
||||
Example:
|
||||
--------
|
||||
>>> lowest = driver.find_element(By.ID, "below")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").above(lowest))
|
||||
>>> ids = [el.get_attribute("id") for el in elements]
|
||||
>>> assert "above" in ids
|
||||
>>> assert "mid" in ids
|
||||
"""
|
||||
|
||||
LocatorType = dict[ByType, str]
|
||||
|
||||
def __init__(self, root: dict[ByType, str] | None = None, filters: list | None = None):
|
||||
"""Create a RelativeBy object (prefer using `locate_with` instead).
|
||||
|
||||
Args:
|
||||
root: A dict with `By` enum as the key and the search query as the value
|
||||
filters: A list of the filters that will be searched. If none are passed
|
||||
in please use the fluent API on the object to create the filters
|
||||
"""
|
||||
self.root = root
|
||||
self.filters = filters or []
|
||||
|
||||
@overload
|
||||
def above(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def above(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def above(self, element_or_locator: WebElement | LocatorType | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements above.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look above
|
||||
|
||||
Returns:
|
||||
RelativeBy
|
||||
|
||||
Raises:
|
||||
WebDriverException: If `element_or_locator` is None.
|
||||
|
||||
Example:
|
||||
--------
|
||||
>>> lowest = driver.find_element(By.ID, "below")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").above(lowest))
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling above method")
|
||||
|
||||
self.filters.append({"kind": "above", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def below(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def below(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def below(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements below.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look below
|
||||
|
||||
Returns:
|
||||
RelativeBy
|
||||
|
||||
Raises:
|
||||
WebDriverException: If `element_or_locator` is None.
|
||||
|
||||
Example:
|
||||
>>> highest = driver.find_element(By.ID, "high")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").below(highest))
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling below method")
|
||||
|
||||
self.filters.append({"kind": "below", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def to_left_of(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def to_left_of(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def to_left_of(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements to the left of.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look to the left of
|
||||
|
||||
Returns:
|
||||
RelativeBy
|
||||
|
||||
Raises:
|
||||
WebDriverException: If `element_or_locator` is None.
|
||||
|
||||
Example:
|
||||
>>> right = driver.find_element(By.ID, "right")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_left_of(right))
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling to_left_of method")
|
||||
|
||||
self.filters.append({"kind": "left", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def to_right_of(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def to_right_of(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def to_right_of(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements right of.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look right of
|
||||
|
||||
Returns:
|
||||
RelativeBy
|
||||
|
||||
Raises:
|
||||
WebDriverException: If `element_or_locator` is None.
|
||||
|
||||
Example:
|
||||
>>> left = driver.find_element(By.ID, "left")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_right_of(left))
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling to_right_of method")
|
||||
|
||||
self.filters.append({"kind": "right", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def straight_above(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def straight_above(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def straight_above(self, element_or_locator: WebElement | LocatorType | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements above.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look above
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling above method")
|
||||
|
||||
self.filters.append({"kind": "straightAbove", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def straight_below(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def straight_below(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def straight_below(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements below.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look below
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling below method")
|
||||
|
||||
self.filters.append({"kind": "straightBelow", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def straight_left_of(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def straight_left_of(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def straight_left_of(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements to the left of.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look to the left of
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling to_left_of method")
|
||||
|
||||
self.filters.append({"kind": "straightLeft", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def straight_right_of(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def straight_right_of(self, element_or_locator: None = None) -> "NoReturn": ...
|
||||
|
||||
def straight_right_of(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
|
||||
"""Add a filter to look for elements right of.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look right of
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling to_right_of method")
|
||||
|
||||
self.filters.append({"kind": "straightRight", "args": [element_or_locator]})
|
||||
return self
|
||||
|
||||
@overload
|
||||
def near(self, element_or_locator: WebElement | LocatorType, distance: int = 50) -> "RelativeBy": ...
|
||||
|
||||
@overload
|
||||
def near(self, element_or_locator: None = None, distance: int = 50) -> "NoReturn": ...
|
||||
|
||||
def near(self, element_or_locator: WebElement | LocatorType | None = None, distance: int = 50) -> "RelativeBy":
|
||||
"""Add a filter to look for elements near.
|
||||
|
||||
Args:
|
||||
element_or_locator: Element to look near by the element or within a distance
|
||||
distance: Distance in pixel
|
||||
|
||||
Returns:
|
||||
RelativeBy
|
||||
|
||||
Raises:
|
||||
WebDriverException: If `element_or_locator` is None
|
||||
WebDriverException: If `distance` is less than or equal to 0.
|
||||
|
||||
Example:
|
||||
>>> near = driver.find_element(By.ID, "near")
|
||||
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").near(near, 50))
|
||||
"""
|
||||
if not element_or_locator:
|
||||
raise WebDriverException("Element or locator must be given when calling near method")
|
||||
if distance <= 0:
|
||||
raise WebDriverException("Distance must be positive")
|
||||
|
||||
self.filters.append({"kind": "near", "args": [element_or_locator, distance]})
|
||||
return self
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Create a dict to be passed to the driver for element searching."""
|
||||
return {
|
||||
"relative": {
|
||||
"root": self.root,
|
||||
"filters": self.filters,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
|
||||
from selenium.common.exceptions import NoSuchElementException, UnexpectedTagNameException
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.remote.webelement import WebElement
|
||||
|
||||
|
||||
class Select:
|
||||
def __init__(self, webelement: WebElement) -> None:
|
||||
"""Constructor. A check is made that the given element is a SELECT tag.
|
||||
|
||||
Args:
|
||||
webelement: SELECT element to wrap
|
||||
|
||||
Example:
|
||||
from selenium.webdriver.support.ui import Select
|
||||
Select(driver.find_element(By.TAG_NAME, "select")).select_by_index(2)
|
||||
|
||||
Raises:
|
||||
UnexpectedTagNameException: If the element is not a SELECT tag
|
||||
"""
|
||||
if webelement.tag_name.lower() != "select":
|
||||
raise UnexpectedTagNameException(f"Select only works on <select> elements, not on {webelement.tag_name}")
|
||||
self._el = webelement
|
||||
multi = self._el.get_dom_attribute("multiple")
|
||||
self.is_multiple = multi and multi != "false"
|
||||
|
||||
@property
|
||||
def options(self) -> list[WebElement]:
|
||||
"""Returns a list of all options belonging to this select tag."""
|
||||
return self._el.find_elements(By.TAG_NAME, "option")
|
||||
|
||||
@property
|
||||
def all_selected_options(self) -> list[WebElement]:
|
||||
"""Return a list of all selected options belonging to this select tag."""
|
||||
return [opt for opt in self.options if opt.is_selected()]
|
||||
|
||||
@property
|
||||
def first_selected_option(self) -> WebElement:
|
||||
"""Return the first selected option or the currently selected option."""
|
||||
for opt in self.options:
|
||||
if opt.is_selected():
|
||||
return opt
|
||||
raise NoSuchElementException("No options are selected")
|
||||
|
||||
def select_by_value(self, value: str) -> None:
|
||||
"""Select all options that have a value matching the argument.
|
||||
|
||||
Example:
|
||||
When given "foo" this would select an option like:
|
||||
|
||||
`<option value="foo">Bar</option>`
|
||||
|
||||
Args:
|
||||
value: The value to match against
|
||||
|
||||
Raises:
|
||||
NoSuchElementException: If there is no option with specified value in SELECT
|
||||
"""
|
||||
css = f"option[value ={self._escape_string(value)}]"
|
||||
opts = self._el.find_elements(By.CSS_SELECTOR, css)
|
||||
matched = False
|
||||
for opt in opts:
|
||||
self._set_selected(opt)
|
||||
if not self.is_multiple:
|
||||
return
|
||||
matched = True
|
||||
if not matched:
|
||||
raise NoSuchElementException(f"Cannot locate option with value: {value}")
|
||||
|
||||
def select_by_index(self, index: int) -> None:
|
||||
"""Select the option at the given index by examining the "index" attribute.
|
||||
|
||||
Args:
|
||||
index: The option at this index will be selected
|
||||
|
||||
Raises:
|
||||
NoSuchElementException: If there is no option with specified index in SELECT
|
||||
"""
|
||||
match = str(index)
|
||||
for opt in self.options:
|
||||
if opt.get_attribute("index") == match:
|
||||
self._set_selected(opt)
|
||||
return
|
||||
raise NoSuchElementException(f"Could not locate element with index {index}")
|
||||
|
||||
def select_by_visible_text(self, text: str) -> None:
|
||||
"""Select all options that display text matching the argument.
|
||||
|
||||
Example:
|
||||
When given "Bar" this would select an option like:
|
||||
|
||||
`<option value="foo">Bar</option>`
|
||||
|
||||
Args:
|
||||
text: The visible text to match against
|
||||
|
||||
Raises:
|
||||
NoSuchElementException: If there is no option with specified text in SELECT
|
||||
"""
|
||||
xpath = f".//option[normalize-space(.) = {self._escape_string(text)}]"
|
||||
opts = self._el.find_elements(By.XPATH, xpath)
|
||||
matched = False
|
||||
for opt in opts:
|
||||
if not self._has_css_property_and_visible(opt):
|
||||
raise NoSuchElementException(f"Invisible option with text: {text}")
|
||||
self._set_selected(opt)
|
||||
if not self.is_multiple:
|
||||
return
|
||||
matched = True
|
||||
|
||||
if len(opts) == 0 and " " in text:
|
||||
sub_string_without_space = self._get_longest_token(text)
|
||||
if sub_string_without_space == "":
|
||||
candidates = self.options
|
||||
else:
|
||||
xpath = f".//option[contains(.,{self._escape_string(sub_string_without_space)})]"
|
||||
candidates = self._el.find_elements(By.XPATH, xpath)
|
||||
for candidate in candidates:
|
||||
if text == candidate.text:
|
||||
if not self._has_css_property_and_visible(candidate):
|
||||
raise NoSuchElementException(f"Invisible option with text: {text}")
|
||||
self._set_selected(candidate)
|
||||
if not self.is_multiple:
|
||||
return
|
||||
matched = True
|
||||
|
||||
if not matched:
|
||||
raise NoSuchElementException(f"Could not locate element with visible text: {text}")
|
||||
|
||||
def deselect_all(self) -> None:
|
||||
"""Clear all selected entries.
|
||||
|
||||
This is only valid when the SELECT supports multiple selections.
|
||||
throws NotImplementedError If the SELECT does not support
|
||||
multiple selections
|
||||
"""
|
||||
if not self.is_multiple:
|
||||
raise NotImplementedError("You may only deselect all options of a multi-select")
|
||||
for opt in self.options:
|
||||
self._unset_selected(opt)
|
||||
|
||||
def deselect_by_value(self, value: str) -> None:
|
||||
"""Deselect all options that have a value matching the argument.
|
||||
|
||||
Example:
|
||||
When given "foo" this would deselect an option like:
|
||||
|
||||
`<option value="foo">Bar</option>`
|
||||
|
||||
Args:
|
||||
value: The value to match against
|
||||
|
||||
Raises:
|
||||
NoSuchElementException: If there is no option with specified value in SELECT
|
||||
"""
|
||||
if not self.is_multiple:
|
||||
raise NotImplementedError("You may only deselect options of a multi-select")
|
||||
matched = False
|
||||
css = f"option[value = {self._escape_string(value)}]"
|
||||
opts = self._el.find_elements(By.CSS_SELECTOR, css)
|
||||
for opt in opts:
|
||||
self._unset_selected(opt)
|
||||
matched = True
|
||||
if not matched:
|
||||
raise NoSuchElementException(f"Could not locate element with value: {value}")
|
||||
|
||||
def deselect_by_index(self, index: int) -> None:
|
||||
"""Deselect the option at the given index by examining the "index" attribute.
|
||||
|
||||
Args:
|
||||
index: The option at this index will be deselected
|
||||
|
||||
Raises:
|
||||
NoSuchElementException: If there is no option with specified index in SELECT
|
||||
"""
|
||||
if not self.is_multiple:
|
||||
raise NotImplementedError("You may only deselect options of a multi-select")
|
||||
for opt in self.options:
|
||||
if opt.get_attribute("index") == str(index):
|
||||
self._unset_selected(opt)
|
||||
return
|
||||
raise NoSuchElementException(f"Could not locate element with index {index}")
|
||||
|
||||
def deselect_by_visible_text(self, text: str) -> None:
|
||||
"""Deselect all options that display text matching the argument.
|
||||
|
||||
Example:
|
||||
when given "Bar" this would deselect an option like:
|
||||
|
||||
`<option value="foo">Bar</option>`
|
||||
|
||||
Args:
|
||||
text: The visible text to match against
|
||||
"""
|
||||
if not self.is_multiple:
|
||||
raise NotImplementedError("You may only deselect options of a multi-select")
|
||||
matched = False
|
||||
xpath = f".//option[normalize-space(.) = {self._escape_string(text)}]"
|
||||
opts = self._el.find_elements(By.XPATH, xpath)
|
||||
for opt in opts:
|
||||
if not self._has_css_property_and_visible(opt):
|
||||
raise NoSuchElementException(f"Invisible option with text: {text}")
|
||||
self._unset_selected(opt)
|
||||
matched = True
|
||||
if not matched:
|
||||
raise NoSuchElementException(f"Could not locate element with visible text: {text}")
|
||||
|
||||
def _set_selected(self, option) -> None:
|
||||
if not option.is_selected():
|
||||
if not option.is_enabled():
|
||||
raise NotImplementedError("You may not select a disabled option")
|
||||
option.click()
|
||||
|
||||
def _unset_selected(self, option) -> None:
|
||||
if option.is_selected():
|
||||
option.click()
|
||||
|
||||
def _escape_string(self, value: str) -> str:
|
||||
if '"' in value and "'" in value:
|
||||
substrings = value.split('"')
|
||||
result = ["concat("]
|
||||
for substring in substrings:
|
||||
result.append(f'"{substring}"')
|
||||
result.append(", '\"', ")
|
||||
result = result[0:-1]
|
||||
if value.endswith('"'):
|
||||
result.append(", '\"'")
|
||||
return "".join(result) + ")"
|
||||
|
||||
if '"' in value:
|
||||
return f"'{value}'"
|
||||
|
||||
return f'"{value}"'
|
||||
|
||||
def _get_longest_token(self, value: str) -> str:
|
||||
items = value.split(" ")
|
||||
longest = ""
|
||||
for item in items:
|
||||
if len(item) > len(longest):
|
||||
longest = item
|
||||
return longest
|
||||
|
||||
def _has_css_property_and_visible(self, option) -> bool:
|
||||
css_value_candidates = ["hidden", "none", "0", "0.0"]
|
||||
css_property_candidates = ["visibility", "display", "opacity"]
|
||||
|
||||
for css_property in css_property_candidates:
|
||||
css_value = option.value_of_css_property(css_property)
|
||||
if css_value in css_value_candidates:
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,21 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
from selenium.webdriver.support.select import Select
|
||||
from selenium.webdriver.support.wait import WebDriverWait
|
||||
|
||||
__all__ = ["Select", "WebDriverWait"]
|
||||
@@ -0,0 +1,161 @@
|
||||
# Licensed to the Software Freedom Conservancy (SFC) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The SFC licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import time
|
||||
from collections.abc import Callable, Iterable
|
||||
from typing import Generic, Literal, TypeVar
|
||||
|
||||
from selenium.common.exceptions import NoSuchElementException, TimeoutException
|
||||
from selenium.webdriver.remote.webdriver import WebDriver
|
||||
from selenium.webdriver.remote.webelement import WebElement
|
||||
|
||||
POLL_FREQUENCY: float = 0.5 # How long to sleep in between calls to the method
|
||||
IGNORED_EXCEPTIONS: tuple[type[Exception]] = (NoSuchElementException,) # default to be ignored.
|
||||
|
||||
D = TypeVar("D", bound=WebDriver | WebElement)
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class WebDriverWait(Generic[D]):
|
||||
def __init__(
|
||||
self,
|
||||
driver: D,
|
||||
timeout: float,
|
||||
poll_frequency: float = POLL_FREQUENCY,
|
||||
ignored_exceptions: Iterable[type[Exception]] | None = None,
|
||||
):
|
||||
"""Constructor, takes a WebDriver instance and timeout in seconds.
|
||||
|
||||
Args:
|
||||
driver: Instance of WebDriver (Ie, Firefox, Chrome or Remote) or
|
||||
a WebElement.
|
||||
timeout: Number of seconds before timing out.
|
||||
poll_frequency: Sleep interval between calls. By default, it is
|
||||
0.5 second.
|
||||
ignored_exceptions: Iterable structure of exception classes ignored
|
||||
during calls. By default, it contains NoSuchElementException only.
|
||||
|
||||
Example:
|
||||
>>> from selenium.webdriver.common.by import By
|
||||
>>> from selenium.webdriver.support.wait import WebDriverWait
|
||||
>>> from selenium.common.exceptions import ElementNotVisibleException
|
||||
>>>
|
||||
>>> # Wait until the element is no longer visible
|
||||
>>> is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException))
|
||||
... .until_not(lambda x: x.find_element(By.ID, "someId").is_displayed())
|
||||
"""
|
||||
self._driver = driver
|
||||
self._timeout = float(timeout)
|
||||
self._poll = poll_frequency
|
||||
# avoid the divide by zero
|
||||
if self._poll == 0:
|
||||
self._poll = POLL_FREQUENCY
|
||||
exceptions: list = list(IGNORED_EXCEPTIONS)
|
||||
if ignored_exceptions:
|
||||
try:
|
||||
exceptions.extend(iter(ignored_exceptions))
|
||||
except TypeError: # ignored_exceptions is not iterable
|
||||
exceptions.append(ignored_exceptions)
|
||||
self._ignored_exceptions = tuple(exceptions)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<{type(self).__module__}.{type(self).__name__} (session="{self._driver.session_id}")>'
|
||||
|
||||
def until(self, method: Callable[[D], Literal[False] | T], message: str = "") -> T:
|
||||
"""Wait until the method returns a value that is not False.
|
||||
|
||||
Calls the method provided with the driver as an argument until the
|
||||
return value does not evaluate to ``False``.
|
||||
|
||||
Args:
|
||||
method: A callable object that takes a WebDriver instance as an
|
||||
argument.
|
||||
message: Optional message for TimeoutException.
|
||||
|
||||
Returns:
|
||||
The result of the last call to `method`.
|
||||
|
||||
Raises:
|
||||
TimeoutException: If 'method' does not return a truthy value within
|
||||
the WebDriverWait object's timeout.
|
||||
|
||||
Example:
|
||||
>>> from selenium.webdriver.common.by import By
|
||||
>>> from selenium.webdriver.support.ui import WebDriverWait
|
||||
>>> from selenium.webdriver.support import expected_conditions as EC
|
||||
>>>
|
||||
>>> # Wait until an element is visible on the page
|
||||
>>> wait = WebDriverWait(driver, 10)
|
||||
>>> element = wait.until(EC.visibility_of_element_located((By.ID, "exampleId")))
|
||||
>>> print(element.text)
|
||||
"""
|
||||
screen = None
|
||||
stacktrace = None
|
||||
|
||||
end_time = time.monotonic() + self._timeout
|
||||
while True:
|
||||
try:
|
||||
value = method(self._driver)
|
||||
if value:
|
||||
return value
|
||||
except self._ignored_exceptions as exc:
|
||||
screen = getattr(exc, "screen", None)
|
||||
stacktrace = getattr(exc, "stacktrace", None)
|
||||
if time.monotonic() > end_time:
|
||||
break
|
||||
time.sleep(self._poll)
|
||||
raise TimeoutException(message, screen, stacktrace)
|
||||
|
||||
def until_not(self, method: Callable[[D], T], message: str = "") -> T | Literal[True]:
|
||||
"""Wait until the method returns a value that is False.
|
||||
|
||||
Calls the method provided with the driver as an argument until the
|
||||
return value evaluates to ``False``.
|
||||
|
||||
Args:
|
||||
method: A callable object that takes a WebDriver instance as an
|
||||
argument.
|
||||
message: Optional message for TimeoutException.
|
||||
|
||||
Returns:
|
||||
The result of the last call to `method`.
|
||||
|
||||
Raises:
|
||||
TimeoutException: If 'method' does not return False within the
|
||||
WebDriverWait object's timeout.
|
||||
|
||||
Example:
|
||||
>>> from selenium.webdriver.common.by import By
|
||||
>>> from selenium.webdriver.support.ui import WebDriverWait
|
||||
>>> from selenium.webdriver.support import expected_conditions as EC
|
||||
>>>
|
||||
>>> # Wait until an element is no longer visible on the page
|
||||
>>> wait = WebDriverWait(driver, 10)
|
||||
>>> is_disappeared = wait.until_not(EC.visibility_of_element_located((By.ID, "exampleId")))
|
||||
"""
|
||||
end_time = time.monotonic() + self._timeout
|
||||
while True:
|
||||
try:
|
||||
value = method(self._driver)
|
||||
if not value:
|
||||
return value
|
||||
except self._ignored_exceptions:
|
||||
return True
|
||||
if time.monotonic() > end_time:
|
||||
break
|
||||
time.sleep(self._poll)
|
||||
raise TimeoutException(message)
|
||||
Reference in New Issue
Block a user