|
| 1 | +# Monkey-patching WebElement.click to add retry logic for unclickable elements. |
| 2 | +# This patch is applied globally to all WebElement instances. |
| 3 | +from selenium.webdriver.remote.webelement import WebElement |
| 4 | +from selenium.webdriver.support import expected_conditions as EC |
| 5 | +from selenium.webdriver.support.wait import WebDriverWait |
| 6 | + |
| 7 | + |
| 8 | +def patched_click_factory(timeout: float): |
| 9 | + """ |
| 10 | + Args: |
| 11 | + timeout (float): Maximum time to wait for the element to become clickable. |
| 12 | + """ |
| 13 | + |
| 14 | + def patched_click(self): |
| 15 | + """ |
| 16 | + Patches the WebElement's click method to wait for the element to be clickable. |
| 17 | + Args: |
| 18 | + self: WebElement object. |
| 19 | + """ |
| 20 | + driver = self.parent |
| 21 | + WebDriverWait(driver, timeout).until(EC.element_to_be_clickable(self)) |
| 22 | + |
| 23 | + self._original_click() |
| 24 | + |
| 25 | + return patched_click |
| 26 | + |
| 27 | + |
| 28 | +def patched_send_keys_factory(timeout: float): |
| 29 | + """ |
| 30 | + Args: |
| 31 | + timeout (float): Maximum time to wait for the element to become clickable. |
| 32 | + """ |
| 33 | + |
| 34 | + def patched_send_keys(self, *args, **kwargs): |
| 35 | + """ |
| 36 | + Patches the WebElement's click method to wait for the element to be clickable. |
| 37 | + Args: |
| 38 | + self: WebElement object. |
| 39 | + """ |
| 40 | + driver = self.parent |
| 41 | + WebDriverWait(driver, timeout).until(EC.element_to_be_clickable(self)) |
| 42 | + |
| 43 | + self._original_send_keys(*args, **kwargs) |
| 44 | + |
| 45 | + return patched_send_keys |
| 46 | + |
| 47 | + |
| 48 | +def enable_autowait(timeout: float=10.0) -> None: |
| 49 | + """ |
| 50 | + Enables auto-waiting globally for all WebDriver.click() invokcations |
| 51 | + Args: |
| 52 | + self: WebElement object. |
| 53 | + timeout (float): Maximum time to wait for the element to become clickable. |
| 54 | + """ |
| 55 | + assert not hasattr(WebElement, "_original_click"), "Autowait already enabled." |
| 56 | + assert not hasattr(WebElement, "_original_send_keys"), "Autowait already enabled." |
| 57 | + WebElement._original_click = WebElement.click |
| 58 | + WebElement.click = patched_click_factory(timeout) |
| 59 | + WebElement._original_send_keys = WebElement.send_keys |
| 60 | + WebElement.send_keys = patched_send_keys_factory(timeout) |
| 61 | + |
| 62 | + |
| 63 | +def disable_autowait() -> None: |
| 64 | + assert hasattr(WebElement, "_original_click"), "Autowait is not enabled." |
| 65 | + assert hasattr(WebElement, "_original_send_keys"), "Autowait is not enabled." |
| 66 | + WebElement.click = WebElement._original_click |
| 67 | + del(WebElement._original_click) |
| 68 | + WebElement.send_keys = WebElement._original_send_keys |
| 69 | + del(WebElement._original_send_keys) |
0 commit comments