How to Handle Textboxes and Buttons in Selenium (Python)

How to Handle Textboxes and Buttons in Selenium (Python)

Selenium is a powerful tool used for automating web applications. One of the most common tasks in Selenium is interacting with textboxes and buttons—like filling out forms or clicking submit.

In this post, you’ll learn how to:

  • Enter text in a textbox

  • Click a button

  • Clear a textbox

  • Check if buttons/textboxes are enabled or visible


Getting Started

First, install Selenium (if not already):

pip install selenium

Also, download the appropriate WebDriver (like ChromeDriver) and place it in your project folder or system path.


๐Ÿ› ️ Basic Setup

from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.get("https://example.com/login") # replace with your target URL

๐Ÿ“ฅ How to Handle Textboxes

๐Ÿ”ธ 1. Find Textbox Element

Use find_element() and a locator like ID, name, or XPath.

textbox = driver.find_element(By.ID, "username")

๐Ÿ”ธ 2. Enter Text

textbox.send_keys("my_username")

๐Ÿ”ธ 3. Clear Text

textbox.clear()

๐Ÿ”ธ 4. Check If Textbox Is Enabled

if textbox.is_enabled(): print("Textbox is enabled")

๐Ÿ–ฑ️ How to Handle Buttons

๐Ÿ”ธ 1. Find the Button

button = driver.find_element(By.ID, "loginBtn")

You can also use:

  • By.NAME

  • By.XPATH

  • By.CSS_SELECTOR

๐Ÿ”ธ 2. Click the Button

button.click()

๐Ÿ”ธ 3. Check If Button Is Visible and Enabled

if button.is_displayed() and button.is_enabled(): print("Button is clickable")

๐Ÿ’ก Example: Simple Login Automation

from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://example.com/login") # Enter username and password driver.find_element(By.ID, "username").send_keys("testuser") driver.find_element(By.ID, "password").send_keys("mypassword") # Click login button driver.find_element(By.ID, "loginBtn").click() # Close browser driver.quit()

⚠️ Best Practices

  • Always use unique locators (ID preferred)

  • Add waits if elements take time to load

    from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "username")) )
  • Use try-except to handle missing elements


๐Ÿ“Œ Summary

TaskSelenium Code
Enter textelement.send_keys("text")
Clear textboxelement.clear()
Click buttonelement.click()
Check visibilityelement.is_displayed()
Check enabledelement.is_enabled()

๐Ÿง  Final Thoughts

Handling textboxes and buttons is the foundation of web automation in Selenium.
With just a few lines of code, you can fill forms, log in to websites, or test UI workflows.


Read More 




Comments

Popular posts from this blog

What is WebDriver in Selenium? Explained with Java

Tosca System Requirements and Installation Guide (Step-by-Step)

Why Choose Python for Full-Stack Web Development