Get label text of a checkbox


Selenium Python - Get label text for a checkbox

In this tutorial, you will learn how to get the label text for a specific checkbox in a webpage, in Selenium Python.

To get the label value of a specific checkbox in Selenium Python, find the checkbox label using find_element() method of the driver object using XPath for the label, and read the text property on the label WebElement object.

The XPath for finding the label element for a specific checkbox is

"//label[@for='label_id']"

Replace label_id with the value of the for attribute in label element. In HTML file, the label would be as shown in the following, and the value of for attribute is "apple" for <label for="apple">.

<input type="checkbox" id="apple" name="apple" value="Apple">
<label for="apple"> I eat apples.</label>

Example

In this example, we shall consider loading the webpage at URL: /tmp/selenium/index-24.html. The contents of this webpage is given below. The webpage contains three checkboxes.

index.html

<html>
 <body>
  <h1>My Sample Form</h1>
  <form id="myform">
    <input type="checkbox" id="apple" name="apple" value="Apple">
    <label for="apple"> I eat apples.</label><br>
    <input type="checkbox" id="banana" name="banana" value="Banana">
    <label for="banana"> I eat bananas.</label><br>
    <input type="checkbox" id="cherry" name="cherry" value="Cherry">
    <label for="cherry"> I eat cherries.</label><br>
  </form>
 </body>
</html>
Selenium Python - Get label value for a checkbox

We shall get the label text of the first checkbox, and print it to the 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
driver = webdriver.Chrome(service=ChromeService(executable_path=ChromeDriverManager().install()))

# Load the url
driver.get('/tmp/selenium/index-24.html')

# Find the label with attribute for='apple'
mylabel = driver.find_element(By.XPATH, "//label[@for='apple']")

# Get label text
labeltext = mylabel.text
print(labeltext)

# Close the driver
driver.quit()

Output

I eat apples.

Summary

In this Python Selenium tutorial, we have given instructions on how to find the label text for a checkbox, with the help of an example program.