form表单元素测试(checkbox和radio)

一、定义form表单

用到的元素:checkbox和radiobutton
下图定义了一个选择爱好和选择性别的form表单,区域1用到的表单元素是checkbox(复选框),区域2用到的表单元素是radiobutton


点击查看代码
<!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)


用例2:反选checkbox选项
结果2:不选中选项
swimming.click()
sleep(2)


三、测试radiobutton

用例1:选中男性
结果1:正常选中
ls=self.driver.find_elements(By.NAME, 'gender')
#find_elements()方法返回一个WebElement对象列表
ls[0].click()
sleep(2)


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

四、代码

点击查看代码
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()