Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 35 ยท Interacting with the Page

Clicking and Typing

Learn the everyday Selenium actions: click, send_keys, clear, special Keys, reading text and attributes, and checking is_displayed, is_enabled and is_selected.

Finding an element is only half of a test. The other half is doing what a user does: clicking a button, typing into a field, pressing Enter, and then checking what the page shows. Selenium keeps this small. A handful of methods on the element object covers the vast majority of everyday browser automation.

In this lesson you will use click, send_keys, clear, the Keys constants, and the methods that read an element back: its text, its attributes and its state. You will also see why some calls fail with an "element not interactable" error and how to tell what the real browser is doing when they do.

Selenium and a browser cannot run on this site, so the Selenium and Python lines are read-only. The runnable examples are JavaScript stand-ins built on events: they model what a browser does when Selenium clicks or types, so you can watch the sequence of events and the failure rules.

The two core actions

Every interaction starts with an element you have already located:

Python
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://example.test/login")

email = driver.find_element(By.ID, "email")
email.send_keys("[email protected]")

login = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
login.click()

click() scrolls the element into view if needed, then clicks the middle of it, like a person would. send_keys(text) focuses the element and types the text one key at a time, firing the same events a real keyboard produces. Because it types real key events, a page's JavaScript that listens for input, keydown or change reacts normally.

Act, then read back

click() Click the middle of the element.
send_keys() Type into the focused element.
clear() Empty a text field.
Read state Text, attributes, displayed, enabled.

Four small tools cover most interactions.

1 / 2

Typing details you will meet right away

send_keys appends to whatever is already in the field. Typing into a field that holds a default value gives you the default followed by your text. Call clear() first when you need a clean field:

Python
search = driver.find_element(By.NAME, "q")
search.clear()
search.send_keys("selenium locators")

clear() empties a text input or textarea. It does not work on other elements, and some frameworks that keep their own state need extra events, in which case you can select all and delete (described below).

To press non-text keys, import Keys:

Python
from selenium.webdriver.common.keys import Keys

search.send_keys("selenium locators", Keys.ENTER)   # type, then press Enter
search.send_keys(Keys.TAB)                          # move focus to the next field
search.send_keys(Keys.ARROW_DOWN, Keys.ARROW_DOWN)  # navigate a list
search.send_keys(Keys.CONTROL, "a")                 # chord: hold Control, press a
search.send_keys(Keys.BACKSPACE)

Keys passed in one call are pressed in order. A modifier such as Keys.CONTROL stays held until the end of that send_keys call, which is how Keys.CONTROL, "a" means "select all". On macOS the select-all modifier is Keys.COMMAND. If your suite runs on several operating systems, a robust way to wipe a field is field.send_keys(Keys.CONTROL, "a", Keys.BACKSPACE), with COMMAND on a Mac, or simply use clear() where it works.

submit() submits the form that contains an element. It is often a shortcut for clicking a submit button, and it is tolerated, but clicking the real button (or pressing Enter) tests what the user actually does, including any JavaScript attached to that button. Prefer the click.

Reading an element back

After acting, you check results by reading the page:

Python
message = driver.find_element(By.ID, "message")

message.text                          # the visible text, as a user sees it
message.get_attribute("class")        # an attribute or property
email.get_attribute("value")          # what is currently typed into an input
email.get_dom_attribute("value")      # only the attribute written in the HTML
message.tag_name                      # "div"
message.value_of_css_property("color")

Some points worth knowing:

  • .text returns only visible text, with whitespace normalised the way the browser renders it. Text hidden with CSS is not returned, which is a common reason for an empty result. If an element is present but hidden, read get_attribute("textContent") to see its raw text.
  • For an input, .text is empty. The typed content lives in the value property: use get_attribute("value").
  • get_attribute returns the property when the element has one and falls back to the HTML attribute. get_dom_attribute reads only the attribute, which is useful when you want the original HTML value. get_property reads only the DOM property.
  • A boolean attribute such as disabled comes back as the string "true" or None, so test with is not None or use the state methods below.

Asking about state

Three methods answer yes/no questions about an element and return True or False:

Method True when
is_displayed() The user can see it: not display: none, not visibility: hidden, not zero size, and not hidden by a closed container
is_enabled() A form control is not disabled
is_selected() A checkbox, radio button or <option> is checked or selected

These do not raise if the answer is "no", but find_element itself raises NoSuchElementException when the element is not in the page at all. A hidden element exists in the page but is not displayed, and that distinction explains most of the exceptions below.

When interaction fails

If an element cannot be interacted with, Selenium raises an exception instead of silently doing nothing. The common ones:

Exception Meaning
ElementNotInteractableException The element exists, but it is hidden, has no size, or cannot receive that input (typing into a div)
ElementClickInterceptedException Another element, such as a cookie banner or a spinner overlay, sits on top of the click point
StaleElementReferenceException The element was found earlier, but the page replaced it since
InvalidElementStateException The action is not valid in the current state, for example clear() on a read-only field

The cure is almost never time.sleep(). It is to wait for the right condition (the overlay to disappear, the element to become clickable), which is the subject of the waiting chapter, beginning with Why Tests Need Waits.

A stand-in: what a click and typing look like to the page

A real browser sends a sequence of events for each user gesture. The stand-in below builds a tiny element with an event log, then implements click and send_keys in terms of events. It uses the EventTarget class that both browsers and Node provide, but not a real page.

JS Click and send_keys as events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows that send_keys("hi") produced a keydown, input and keyup for each character, and that a second call appended instead of replacing. A page that validates on every keystroke would run twice here, just as it does in a real browser. The disabled button ignored the click.

A stand-in: state queries and failures

The second stand-in wraps three elements and asks the three state questions. It also shows the error you get for typing into something hidden, and how a page that "shows" a field later changes what the script can do.

JS is_displayed, is_enabled, is_selected and errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a real test, the step "the field appeared" is where you would use an explicit wait. Without it the script races the page, a problem the next chapter takes apart.

Practical habits

  • Assert on outcomes. After a click, check the new state of the page (a message, a changed URL, a count) instead of assuming it worked.
  • Click the real thing. Prefer clicking a button over submit() or JavaScript clicks, so the test uses the same path as a user. A JavaScript click, driver.execute_script("arguments[0].click()", el), bypasses the overlay check and can hide real usability bugs, so keep it as a workaround, not a default.
  • Clear before typing in fields that might hold a default value, and verify with get_attribute("value").
  • Never type secrets into logs. If a test types a password with send_keys, keep the value in an environment variable, not in the source code or in printed output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A text field already contains "abc". What does field.send_keys("def") leave in it?

    send_keys types at the end of the existing content, so it appends. Call clear() first when you need an empty field.
  2. 2. How do you read what is currently typed into an <input> element?

    The text of an input is empty. Its typed content is in the value property, which get_attribute("value") returns.
  3. 3. A click raises ElementClickInterceptedException. What is the most likely cause?

    That exception means the element was found and visible but something else would receive the click. Wait for the overlay to go away or dismiss it.
  4. 4. Which call presses Enter after typing in a search box?

    Keys from the Keys class are sent through send_keys, in order. Passing text and then Keys.ENTER types the text and presses Enter.

Summary

  • click() scrolls to the element and clicks its middle; send_keys() types real key events and appends to existing text; clear() empties a text field.
  • Special keys come from Keys; modifiers such as Keys.CONTROL stay held for the rest of the call, so Keys.CONTROL, "a" selects all.
  • Read results with .text (visible text only), get_attribute("value") for inputs, and get_dom_attribute for the original HTML attribute.
  • is_displayed(), is_enabled() and is_selected() answer state questions without raising.
  • Interaction exceptions describe the cause (ElementNotInteractable, ElementClickIntercepted, StaleElementReference) and are fixed by waiting for the right condition, not by sleeping.

Next, work with selects, checkboxes and whole forms in Forms, Checkboxes and Dropdowns.