form表單元素測試(checkbox和radio)

jongjongjong發表於2024-10-21

一、定義form表單

用到的元素:checkbox和radiobutton
下圖定義了一個選擇愛好和選擇性別的form表單,區域1用到的表單元素是checkbox(核取方塊),區域2用到的表單元素是radiobutton
image


點選檢視程式碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="javascript:alert('test')">
    swimming:<input type="checkbox" name="swimming" value="swimming"><br>
    reading:<input type="checkbox" name="reading" value="reading"><br>
<hr>
    gender<br>
    <input type="radio" name="gender" value="male" text="male"><label>male</label><br>
    <input type="radio" name="gender" value="female" text="female"><label>female</label><br>
    <input type="submit" name="login" value="login">
</form>
</body>
</html>

二、測試checkbox

用例1:選中checkbox選項
預期結果1:正常選中
swimming=self.driver.find_element(By.NAME, 'swimming')#定位元素
if not swimming.is_selected():
    swimming.click() #選中swimming

reading=self.driver.find_element(By.NAME, 'reading')#定位元素
if not reading.is_selected():
    reading.click()  #選中reading
sleep(10)

image


用例2:反選checkbox選項
結果2:不選中選項
swimming.click()
sleep(2)

image


三、測試radiobutton

用例1:選中男性
結果1:正常選中
ls=self.driver.find_elements(By.NAME, 'gender')
#find_elements()方法返回一個WebElement物件列表
ls[0].click()
sleep(2)

image


用例2:選中女性
結果2:正常選中
ls=self.driver.find_elements(By.NAME, 'gender')
ls[1].click()
sleep(2)

image

四、程式碼

點選檢視程式碼
from selenium import webdriver
from time import sleep
import os
from selenium.webdriver.common.by import By

class TestCase:
    def __init__(self):
        self.driver = webdriver.Edge()
        path = os.path.dirname(os.path.abspath(__file__))  # 獲取當前路徑的父目錄
        file_path = 'file:///' + path + '/form1.html'  # 獲取form表單完整路徑
        self.driver.get(file_path)  # 載入form表單

    def test_checkbox(self):
        swimming=self.driver.find_element(By.NAME, 'swimming')
        if not swimming.is_selected():
            swimming.click()# 選中swimming
        reading=self.driver.find_element(By.NAME, 'reading')
        if not reading.is_selected():
            reading.click()  # 選中reading
        sleep(2)

        swimming.click()
        sleep(2)
        self.driver.quit()

    def test_radio(self):
        ls=self.driver.find_elements(By.NAME, 'gender')
        #ls[0].click()
        ls[1].click()
        sleep(2)
        self.driver.quit()

if __name__=="__main__":
    case = TestCase()
    #case.test_checkbox()
    case.test_radio()

相關文章