Check if input text field is empty in Selenium - Python Examples
Selenium Python - Check if input text field is empty
In this tutorial, you will learn how to check if an input text field is empty in Selenium Python.
To check if an input text field is empty in Selenium Python, you can use get_attribute() method of the input text field object to retrieve the value of value attribute, and then check if the value is empty by comparing the value with an empty string.
The following is a simple code snippet to check if the value in input_text_1 is empty.
value = input_text_1.get_attribute('value')
if value == '':
print("Input text field is empty.")
Example
In this example, we shall consider loading the webpage at URL: /tmp/selenium/index-18.html. The contents of this HTML file is given below. The webpage contains a couple of input text fields.
<html>
<body>
<h3>My Form</h3>
<form action="">
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname"><br><br>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In the following program, we initialize a Chrome webdriver, navigate to specified URL, get the input text field whose name attribute is "firstname"
, check if the value present in the input text field is empty, and print the result to standard output.
Python Program
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
# Setup chrome driver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Navigate to the url
driver.get('/tmp/selenium/index-18.html')
# Get the input text field
input_text_1 = driver.find_element(By.XPATH, "//input[@name='firstname']")
# Get the value in input text field
value = input_text_1.get_attribute('value')
# Check if value is empty
if value == '':
print("Input text field is empty.")
else:
print("Input text field is not empty.")
# Take screenshot
driver.save_screenshot("screenshot.png")
# Close the driver
driver.quit()
Output
Input text field is empty.
screenshot.png
Reference Tutorials
Summary
In this Python Selenium tutorial, we have given instructions on how to check if an input text field is empty or not, with the help of examples.