When performing automated testing with Selenium, clearing the default value from a text field is a common operation. This can be achieved by using Selenium's clear() method. Below are the specific steps and example code to implement this operation:
Steps:
- Locate the Element: First, we need to locate the target text input field using Selenium's locator methods.
- Clear the Content: Use the
clear()method to remove the default value or existing text from the input field.
Example Code:
Assume we have an HTML file containing an input field with a default value:
html<!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <input type="text" id="inputField" value="Default Value"/> </body> </html>
We will use Python and Selenium to write a script to clear the default value from this input field:
pythonfrom selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time # Launch Chrome browser driver = webdriver.Chrome() # Open the webpage containing the input field driver.get("file:///path/to/your/html/file.html") # Locate the input field input_field = driver.find_element(By.ID, "inputField") # Clear the default value from the input field input_field.clear() # Optional: Enter new text to verify the clearing was successful input_field.send_keys("New input text") # Pause for a moment to observe, then close the browser time.sleep(5) driver.quit()
In this example, we use the clear() method to remove the default value from the input field. This method is straightforward and effective for most text input scenarios. Note that in certain specific cases, if the clear() method does not work, it may be necessary to first simulate clicking the input field and then use keyboard operations (such as sending Keys.BACK_SPACE) to delete the text.