My eight brothers learn from Selenium(3): how to operate check box / radio box

Check box and radio box are two controls that are often used in Web sites. How to use Selenium to operate these two controls in web automation testing? Today, let's have a brief introduction practice!

The html test page code is as follows:

  <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
  <title>learn Python network - selenium Learning test page</title> 
  <h2>Please choose your favorite development language</h2> 
   <p><input type="checkbox" id="c1" />C/C++</p>
   <p><input type="checkbox" id="c2" />Java</p>
   <p><input type="checkbox" id="c3" />Python</p>
   <p><input type="checkbox" id="c4" />PHP</p>
   <p><input type="checkbox" id="c5" />Golang</p>
  <h2>Do you like your present job?</h2> 
   <p><input type="radio" name="lovework" value="love" id="rlove" />like</p>
   <p><input type="radio" name="lovework" value="hate" id="rhate" />Dislike</p>
   <p><input type="radio" name="lovework" value="none" id="rnone" />Indifferent</p>

From the HTML code, the check box and radio box are input tags, so we can traverse all the input tag elements, and these elements also have IDS, so the find element by id and find element by XPath operation of individual elements are also feasible.

Python code practice:

# Autor: 5bug
# WebSite:
# Learn Python QQ group: 643829693
from selenium import webdriver

driver = webdriver.Chrome("C:/Users/5bug/AppData/Local/Google/Chrome/Application/chromedriver.exe")

#Traverse to get the checkbox/radio, and check the specified checkbox/radio
inputs = driver.find_elements_by_tag_name("input")
for input in inputs:
    # Read element id
    attr_id = input.get_attribute("id")
    element_type = input.get_attribute("type")
    if element_type == "checkbox":
        #Check if the id is in the id array of hobbies
        if input.is_enabled() & (attr_id in ["c1", "c3"]) & (not input.is_selected()):
    elif element_type == "radio":
        #Check "like your current job"
        if (attr_id == "rlove") & input.is_enabled() & (not input.is_selected()):

The following methods are used:

  • Find elements by tag name

  • Get attribute get an attribute

  • The is? Enabled method is used to determine whether it is available

  • Is [selected method is used to determine whether to select

  • The is? Displayed method is used to determine whether to display

The operation output is as follows:

This article was first published on Python

Tags: Python Selenium Attribute network

Posted on Sat, 04 Apr 2020 15:15:11 -0700 by coolex