1. 程式人生 > 實用技巧 >python+selenium2自動化---CheckBox和radiobutton定位

python+selenium2自動化---CheckBox和radiobutton定位

下面直接通過示例程式碼說明

本地寫一個簡單的form表單:

#form1.html
<!
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> <br> gender:<label><input type="radio" name="gender" value="Male"></label> <label><input type="radio" name="gender" value="Female"></
label> <br> <input type="submit" value="login"> </form> </body> </html>

py測試程式碼:

from selenium import webdriver
import os
from time import sleep


class TestCase():
    def __init__(self):
        self.driver = webdriver.Chrome()
        html_path = os.path.dirname(os.path.abspath(__file__
)) # 本地的html檔案地址拼接 file_path = "file:///" + html_path + '/form1.html' self.driver.get(file_path) def test_checbox(self): swimming = self.driver.find_element_by_name('swimming') reading = self.driver.find_element_by_name('reading') sleep(3)
# 如果沒有被選中,則選中 if not swimming.is_selected(): swimming.click() if not reading.is_selected(): reading.click() sleep(3)
# 反選操作 swimming.click() reading.click() sleep(3) self.driver.quit() def test_radio(self): gender = self.driver.find_elements_by_name('gender') # 可以通過屬性值來判斷勾選哪個值 for el in gender: if el.get_attribute('value') == 'Male': el.click() print('') sleep(2) # 也可以直接勾選第二個標籤元素 gender[1].click() sleep(3) self.driver.quit() if __name__ == '__main__': TestCase().test_radio()