diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..136e19a --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,26 @@ +name: check + +on: + push: + branches: [master] + pull_request: + schedule: + # Monthly, so a new Selenium release that removes a method fails here. + - cron: "0 5 1 * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + methods-exist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + - run: pip install --upgrade selenium + - run: python tools/check_methods.py diff --git a/Action_Chains_Methods.md b/Action_Chains_Methods.md index 25899e3..c819cd5 100644 --- a/Action_Chains_Methods.md +++ b/Action_Chains_Methods.md @@ -1,22 +1,39 @@ +# Action chains -**module:** selenium.webdriver.common.action_chains +Module `selenium.webdriver.common.action_chains`. Each method queues an action +and returns the chain, so calls can be chained; nothing happens until +`perform()`. ---- +```python +from selenium.webdriver.common.action_chains import ActionChains +from selenium.webdriver.common.keys import Keys -| Method Name | Description | Args | Usage | -|---|---|---|---| -| perform | Performs all stored actions | | perform() | -| Click | Clicks an element. | *on_element:* The element to click. If None, clicks on current mouse position. | click(on_element=None) | -| click_and_hold | Holds down the left mouse button on an element. | *on_element:* The element to mouse down. If None, clicks on current mouse position. | click_and_hold(on_element) | -| context_click(Right Click) | Performs a context-click (right click) on an element. | *on_element:* The element to context-click. If None, clicks on current mouse position. | context_click(on_element) | -|double_click | Double-clicks an element. | *on_element:* The element to double-click. If None, clicks on current mouse position. | double_click(on_element) | -| drag_and_drop | Holds down the left mouse button on the source element, then moves to the target element and releases the mouse button. | *source:* The element to mouse down. *target:* The element to mouse up. | drag_and_drop(source, target) | -| key_down | Sends a key press only, without releasing it. Should only be used with modifier keys (Control, Alt and Shift). | *key:* The modifier key to send. Values are defined in Keys class. *element:* The element to send keys. If None, sends a key to current focused element. | key_down(key, element=None) | -| key_up | Releases a modifier key. | *key:* The modifier key to send. Values are defined in Keys class. *element:* The element to send keys. If None, sends a key to current focused element. - | key_up(key, element=None) | -| move_by_offset | Moving the mouse to an offset from current mouse position. | *xoffset:* X offset to move to. *yoffset:* Y offset to move to. | move_by_offset(xoffset, yoffset) | -| move_to_element | Moving the mouse to the middle of an element. | *to_element:* The element to move to. | move_to_element(to_element) | -| move_to_element_with_offset | Move the mouse by an offset of the specificed element. Offsets are relative to the top-left corner of the element. | *to_element:* The element to move to. *xoffset:* X offset to move to. *yoffset:* Y offset to move to. | move_to_element_with_offset(to_element, xoffset, yoffset) | -| release | Releasing a held mouse button. | *on_element:* The element to mouse up. | release(on_element) | -| Send_keys | Sends keys to current focused element. | *keys_to_send:* The keys to send. | Send_keys(`*keys_to_send`) | -| Send_keys_to_element | Sends keys to an element. | *element:* The element to send keys. *keys_to_send:* The keys to send. | Send_keys_to_element(self, element, `*keys_to_send`): | +ActionChains(driver).move_to_element(menu).click(item).perform() +ActionChains(driver).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform() +``` + + +| Method | Description | Usage | +|---|---|---| +| `perform` | Runs all queued actions. | `actions.perform()` | +| `reset_actions` | Clears queued actions and releases held keys and buttons. | `actions.reset_actions()` | +| `click` | Clicks an element, or the current mouse position if none is given. | `actions.click(button)` | +| `click_and_hold` | Presses the left button down on an element. | `actions.click_and_hold(slider)` | +| `context_click` | Right-clicks an element. | `actions.context_click(row)` | +| `double_click` | Double-clicks an element. | `actions.double_click(cell)` | +| `release` | Releases the held mouse button. | `actions.release()` | +| `drag_and_drop` | Drags `source` onto `target`. | `actions.drag_and_drop(card, column)` | +| `drag_and_drop_by_offset` | Drags `source` by an x/y offset. | `actions.drag_and_drop_by_offset(handle, 100, 0)` | +| `move_to_element` | Moves the mouse to the centre of an element. | `actions.move_to_element(menu)` | +| `move_to_element_with_offset` | Moves to an offset from the element's centre (Selenium 4 changed this from the top-left corner). | `actions.move_to_element_with_offset(canvas, 10, -5)` | +| `move_by_offset` | Moves the mouse by an offset from where it is. | `actions.move_by_offset(20, 0)` | +| `key_down` | Presses a modifier key (Control, Alt, Shift) without releasing it. | `actions.key_down(Keys.SHIFT)` | +| `key_up` | Releases a modifier key. | `actions.key_up(Keys.SHIFT)` | +| `send_keys` | Types into the focused element. | `actions.send_keys("hello")` | +| `send_keys_to_element` | Clicks an element, then types into it. | `actions.send_keys_to_element(field, "hello")` | +| `scroll_to_element` | Scrolls until the element is in view. | `actions.scroll_to_element(footer)` | +| `scroll_by_amount` | Scrolls the page by a delta. | `actions.scroll_by_amount(0, 500)` | +| `scroll_from_origin` | Scrolls from an element or point, e.g. inside a scrollable box. | `actions.scroll_from_origin(ScrollOrigin.from_element(box), 0, 200)` | +| `pause` | Waits between queued actions. | `actions.pause(0.5)` | + +`ScrollOrigin` is in `selenium.webdriver.common.actions.wheel_input`. diff --git a/README.md b/README.md index 85cbfda..2f1b71d 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,48 @@ -# Intro -This Repository shall be one stop shop to see all python selenium methods at a glance by modules - -- [Webdriver](https://github.com/surevs/python-selenium-method-collection/blob/master/webdriver-methods.md) - - [General](https://github.com/surevs/python-selenium-method-collection/blob/master/webdriver-methods.md) - - [Target Locators](https://github.com/surevs/python-selenium-method-collection/blob/master/webdriver-methods.md#target-locators) - - [Navigation](https://github.com/surevs/python-selenium-method-collection/blob/master/webdriver-methods.md#navigation) - - [options](https://github.com/surevs/python-selenium-method-collection/blob/master/webdriver-methods.md#options) - - [TimeOuts](https://github.com/surevs/python-selenium-method-collection/blob/master/webdriver-methods.md#timeouts) -- [Handling Alerts](https://github.com/surevs/python-selenium-method-collection/blob/master/alert-methods.md) -- [Action chains](https://github.com/surevs/python-selenium-method-collection/blob/master/Action_Chains_Methods.md) - -Please feel free to share your feedback.. +# Python Selenium method collection + +All the Python Selenium methods you reach for, at a glance, grouped by module. +Updated for Selenium 4; every name in these tables is checked against the +latest Selenium release in CI, so the docs fail loudly when Selenium changes. + +- [WebDriver](webdriver-methods.md) + - [Finding elements](webdriver-methods.md#finding-elements) and [relative locators](webdriver-methods.md#relative-locators) + - [General](webdriver-methods.md#general) + - [Windows and tabs](webdriver-methods.md#windows-and-tabs) + - [Switching context](webdriver-methods.md#switching-context) + - [Navigation](webdriver-methods.md#navigation) + - [Cookies](webdriver-methods.md#cookies) + - [Timeouts](webdriver-methods.md#timeouts) + - [Screenshots](webdriver-methods.md#screenshots) + - [Removed in Selenium 4](webdriver-methods.md#removed-in-selenium-4) +- [WebElement](element-methods.md) +- [Waits and select boxes](waits.md) +- [Alerts](alert-methods.md) +- [Action chains](Action_Chains_Methods.md) + +## Quick start + +```sh +pip install selenium +``` + +```python +from selenium import webdriver +from selenium.webdriver.common.by import By + +driver = webdriver.Chrome() # Selenium Manager downloads a matching driver +driver.get("https://example.com") +print(driver.find_element(By.TAG_NAME, "h1").text) +driver.quit() +``` + +Selenium 4.6 and later find or download the browser driver for you, so there +is no `executable_path` and no separate driver download. + +## Check the docs yourself + +```sh +pip install -U selenium +python tools/check_methods.py +``` + +Feedback and pull requests are welcome. diff --git a/alert-methods.md b/alert-methods.md index 36ad700..986837c 100644 --- a/alert-methods.md +++ b/alert-methods.md @@ -1,15 +1,19 @@ -# module: selenium.webdriver.common.alert -# class Alert(driver) +# Alerts -alert = self.driver.switch_to_alert() +Module `selenium.webdriver.common.alert`, class `Alert`. ---- +```python +alert = driver.switch_to.alert +# or wait for it: +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.wait import WebDriverWait +alert = WebDriverWait(driver, 5).until(EC.alert_is_present()) +``` -| Method Name | Description | Args | Usage | -|---|---|---|---| -| text | Gets the text of the Alert | | alert.text | -| dismiss | Dismisses the alert available | | alert.dismiss() | -| accept | Accepts the alert available | | alert.accept() | -| send_keys | Send Keys to the Alert | *keysToSend:* Any character. | alert.send_keys() | - ---- + +| Method | Description | Usage | +|---|---|---| +| `text` | Text of the alert. | `alert.text` | +| `accept` | Clicks OK. | `alert.accept()` | +| `dismiss` | Clicks Cancel. | `alert.dismiss()` | +| `send_keys` | Types into a `prompt()` dialog. | `alert.send_keys("hello")` | diff --git a/element-methods.md b/element-methods.md new file mode 100644 index 0000000..c54d90e --- /dev/null +++ b/element-methods.md @@ -0,0 +1,43 @@ +# WebElement methods + +What `find_element` returns. Module `selenium.webdriver.remote.webelement`. + + +## Acting on an element + +| Method | Description | Usage | +|---|---|---| +| `click` | Clicks the element. | `button.click()` | +| `send_keys` | Types text or keys; also uploads a file to ``. | `field.send_keys("hello", Keys.ENTER)` | +| `clear` | Clears a text field. | `field.clear()` | +| `submit` | Submits the form the element belongs to. | `form.submit()` | + +## Reading an element + +| Method | Description | Usage | +|---|---|---| +| `text` | Visible text. | `heading.text` | +| `tag_name` | Tag name. | `el.tag_name` | +| `get_dom_attribute` | Attribute exactly as written in the HTML. | `link.get_dom_attribute("href")` | +| `get_property` | Live JavaScript property. | `field.get_property("value")` | +| `get_attribute` | Property if one exists, otherwise the attribute (legacy mix of the two above). | `field.get_attribute("value")` | +| `value_of_css_property` | Computed CSS value. | `el.value_of_css_property("color")` | +| `accessible_name` | Name exposed to assistive technology. | `button.accessible_name` | +| `aria_role` | Computed ARIA role. | `el.aria_role` | +| `is_displayed` | Visible on the page. | `el.is_displayed()` | +| `is_enabled` | Not disabled. | `button.is_enabled()` | +| `is_selected` | Checkbox, radio or option is selected. | `checkbox.is_selected()` | +| `rect` | `x`, `y`, `width`, `height`. | `el.rect` | +| `location` | `x` and `y`. | `el.location` | +| `size` | `width` and `height`. | `el.size` | +| `screenshot` | Saves a PNG of just this element. | `el.screenshot("/tmp/el.png")` | + +## Searching inside an element + +| Method | Description | Usage | +|---|---|---| +| `find_element` | First match inside this element. | `row.find_element(By.TAG_NAME, "td")` | +| `find_elements` | All matches inside this element. | `table.find_elements(By.TAG_NAME, "tr")` | +| `shadow_root` | The element's open shadow root. | `host.shadow_root.find_element(By.CSS_SELECTOR, "button")` | + +A shadow root supports `find_element` and `find_elements` with CSS selectors. diff --git a/tools/check_methods.py b/tools/check_methods.py new file mode 100644 index 0000000..8ff2ab0 --- /dev/null +++ b/tools/check_methods.py @@ -0,0 +1,55 @@ +"""Check that every method named in the docs exists in the installed Selenium. + +Each table follows a marker comment such as +````. The first column of +every table row under a marker must name an attribute of that class or module. +Run with ``python tools/check_methods.py``; it exits 1 and lists anything +Selenium no longer has, so stale docs fail CI instead of misleading readers. +""" + +from __future__ import annotations + +import importlib +import re +import sys +from pathlib import Path + +import selenium + +ROOT = Path(__file__).resolve().parent.parent +MARKER = re.compile(r"") +FIRST_CELL = re.compile(r"^\|\s*`([A-Za-z_][\w]*)`") + + +def resolve(dotted: str) -> object: + try: + return importlib.import_module(dotted) + except ModuleNotFoundError: + module, _, name = dotted.rpartition(".") + return getattr(importlib.import_module(module), name) + + +def main() -> int: + missing: list[str] = [] + checked = 0 + for doc in sorted(ROOT.glob("*.md")): + target = None + target_name = "" + for lineno, line in enumerate(doc.read_text(encoding="utf-8").splitlines(), 1): + if m := MARKER.search(line): + target_name = m.group(1) + target = resolve(target_name) + continue + if target is None or not (m := FIRST_CELL.match(line)): + continue + checked += 1 + if not hasattr(target, m.group(1)): + missing.append(f"{doc.name}:{lineno}: {target_name} has no {m.group(1)!r}") + print(f"selenium {selenium.__version__}: checked {checked} documented names") + for item in missing: + print(item) + return 1 if missing or checked == 0 else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/waits.md b/waits.md new file mode 100644 index 0000000..8d445f4 --- /dev/null +++ b/waits.md @@ -0,0 +1,72 @@ +# Waits and select boxes + +## Explicit waits + +```python +from selenium.webdriver.common.by import By +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.wait import WebDriverWait + +wait = WebDriverWait(driver, timeout=10) +button = wait.until(EC.element_to_be_clickable((By.ID, "save"))) +``` + + +| Method | Description | Usage | +|---|---|---| +| `until` | Polls until the condition returns something truthy, then returns it; raises `TimeoutException` otherwise. | `wait.until(EC.title_is("Home"))` | +| `until_not` | Polls until the condition returns something falsy. | `wait.until_not(EC.visibility_of(spinner))` | + +`WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)`. +Any callable that takes the driver works as a condition: +`wait.until(lambda d: d.find_element(By.ID, "total").text != "")`. + + +### Expected conditions + +Conditions ending in `_located` take a locator tuple such as `(By.ID, "save")`; +the others take an element. + +| Condition | Waits until | Usage | +|---|---|---| +| `presence_of_element_located` | the element is in the DOM | `EC.presence_of_element_located((By.ID, "x"))` | +| `visibility_of_element_located` | the element is in the DOM and visible | `EC.visibility_of_element_located((By.ID, "x"))` | +| `visibility_of` | a found element is visible | `EC.visibility_of(el)` | +| `invisibility_of_element_located` | the element is hidden or gone | `EC.invisibility_of_element_located((By.ID, "spinner"))` | +| `element_to_be_clickable` | the element is visible and enabled | `EC.element_to_be_clickable((By.ID, "save"))` | +| `staleness_of` | an element is detached from the DOM | `EC.staleness_of(old_row)` | +| `text_to_be_present_in_element` | the element's text contains a string | `EC.text_to_be_present_in_element((By.ID, "msg"), "Saved")` | +| `title_is` | the title equals a string | `EC.title_is("Home")` | +| `title_contains` | the title contains a string | `EC.title_contains("Home")` | +| `url_contains` | the URL contains a string | `EC.url_contains("/dashboard")` | +| `url_to_be` | the URL equals a string | `EC.url_to_be("https://example.com/")` | +| `number_of_windows_to_be` | that many windows are open | `EC.number_of_windows_to_be(2)` | +| `new_window_is_opened` | a window opened beyond the given handles | `EC.new_window_is_opened(handles)` | +| `frame_to_be_available_and_switch_to_it` | a frame exists, then switches to it | `EC.frame_to_be_available_and_switch_to_it("editor")` | +| `alert_is_present` | an alert is open, then returns it | `EC.alert_is_present()` | +| `any_of` | any of several conditions holds | `EC.any_of(EC.title_is("A"), EC.title_is("B"))` | +| `all_of` | all of several conditions hold | `EC.all_of(c1, c2)` | +| `none_of` | none of several conditions holds | `EC.none_of(c1, c2)` | + +## Select boxes + +```python +from selenium.webdriver.support.select import Select + +country = Select(driver.find_element(By.ID, "country")) +country.select_by_visible_text("India") +``` + + +| Method | Description | Usage | +|---|---|---| +| `options` | All `