1. 程式人生 > >吾八哥學Selenium(三):操作復選框checkbox/單選框radio的方法

吾八哥學Selenium(三):操作復選框checkbox/單選框radio的方法

attr webdriver for in tex 如果 Go 測試的 har selected

復選框checkbox和單選框radio是web網站裏經常會使用到的兩個控件,那麽在web自動化測試的時候如何利用Selenium來操作這倆控件呢?今天我們就來簡單入門練習一下!

html測試頁面代碼如下:

<html>
 <head> 
  <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
  <title>學Python網 - selenium學習測試頁面</title> 
 </head> 
 <body> 
  <h2>請選擇你喜歡的開發語言</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>您是否喜歡您現在的工作?</h2> 
  <form> 
   <p><input type="radio" name="lovework" value="love" id="rlove" />喜歡</p>
   <p><input type="radio" name="lovework" value="hate" id="rhate" />不喜歡</p>
   <p><input type="radio" name="lovework" value="none" id="rnone" />無所謂</p>
  </form>  
 </body>
</html>

從HTML代碼看,這裏面的復選框checkbox和單選框radio都是input標簽,那麽我們可以遍歷出所有的input標簽元素了,而且這些元素也都有id,所以find_element_by_id和find_element_by_xpath操作單個元素也都是可行的。

Python代碼練習:

# Autor: 5bug
# WebSite: http://www.XuePython.wang
# 學Python網QQ群: 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‘)

#遍歷得到checkbox/radio,並勾選指定的checkbox/radio
inputs = driver.find_elements_by_tag_name("input")
for input in inputs:
    # 讀取元素id
    attr_id = input.get_attribute("id")
    print(attr_id)
    element_type = input.get_attribute("type")
    if element_type == "checkbox":
        #如果id在愛好的id數組內則勾選
        if input.is_enabled() & (attr_id in ["c1", "c3"]) & (not input.is_selected()):
            input.click()
    elif element_type == "radio":
        #勾選喜歡現在的工作選項
        if (attr_id == "rlove") & input.is_enabled() & (not input.is_selected()):
            input.click() 

這裏用到了下面幾個方法:

  • find_elements_by_tag_name根據標簽名稱獲得元素列表

  • get_attribute獲取某個屬性

  • is_enabled方法是用於判斷是否可用

  • is_selected方法是用於判斷是否選中

  • is_displayed方法是用於判斷是否顯示

運行輸出結果如下:

技術分享圖片

本文首發於學Python網:http://www.XuePython.wang

吾八哥學Selenium(三):操作復選框checkbox/單選框radio的方法