In the process of using Selenium for automated testing or automation tasks, manipulating HTML text input fields, such as clearing all content from them, is a common requirement. This can be achieved through the following steps:
-
Locate the Element: First, use Selenium's methods to locate the text input element. Common methods include
find_element_by_id,find_element_by_name, andfind_element_by_xpath. -
Clear the Content: Use the
clear()method to clear the content from the text input field.
Here is a specific example. Suppose we have an HTML page containing a text input field with the ID input-text. We need to clear the content from this text input field:
pythonfrom selenium import webdriver # Launch a Chrome browser instance driver = webdriver.Chrome() # Open the specified URL driver.get('http://example.com') # Locate the text input element input_box = driver.find_element_by_id('input-text') # Clear the content from the text input field input_box.clear() # Close the browser driver.quit()
In this example, the clear() method clears all content from the located text input field. This is very useful for scenarios such as resetting forms or clearing search boxes.
Note that before using the clear() method, ensure the element has been correctly located and is an editable text input field. If attempting to use clear() on elements that are not text input fields, such as labels or buttons, Selenium will throw an error.