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:

<html>
 <head> 
  <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
  <title>learn Python network - selenium Learning test page</title> 
 </head> 
 <body> 
  <h2>Please choose your favorite development language</h2> 
  <form> 
   <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>
  </form> 
  <h2>Do you like your present job?</h2> 
  <form> 
   <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>
  </form>  
 </body>
</html>

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: http://www.XuePython.wang
# Learn Python QQ group: 643829693
from selenium import webdriver

driver = webdriver.Chrome("C:/Users/5bug/AppData/Local/Google/Chrome/Application/chromedriver.exe")
driver.maximize_window()
driver.get('file:///E:\MyCodes\Python\demos\XuePython.wang\html\check_radio.html')

#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")
    print(attr_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()):
            input.click()
    elif element_type == "radio":
        #Check "like your current job"
        if (attr_id == "rlove") & input.is_enabled() & (not input.is_selected()):
            input.click() 

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 http://www.XuePython.wang

Tags: Python Selenium Attribute network

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