form表单中经常涉及复选框(checkbox)和单选框(radiobox),如用户的爱好跑步、游泳、跳舞可以使用复选框,性别男、女可以使用单选框。
(1)checkbox选择或反选:使用click()方法
(2)radiobox有相同的名称,多个值,可先通过名称获得,再通过值判断,选择使用click()方法。
示例页面:
![](https://img-blog.csdnimg.cn/direct/c698196f4940410ab5e6e015b7abddd7.png)
页面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html> <html lang = "en" > <head> <meta charset = "UTF-8" > <title>Title< / title> < / head> <body> <form action = "javascript:alert('selenium操作表单中checkbox和radiobutton')" > 测试 from 表单操作checkbox和radiobutton<br> 跑步:< input type = "checkbox" name = "running" value = "running" ><br> 游泳:< input type = "checkbox" name = "swimming" value = "swimming" ><br> 跳舞:< input type = "checkbox" name = "dancing" value = "dancing" ><br> <! - - <hr>分界线 - - > <hr> 性别:<br> 男:< input type = "radio" name = "gender" value = "male" ><br> 女:< input type = "radio" name = "gender" value = "female" ><br> < input type = "submit" value = "login" > < / form> < / body> < / html> |
示例脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import os from selenium import webdriver from time import sleep class TestCheckBoxOrRadioBtn( object ): def setup( self ): self .driver = webdriver.Chrome() path = os.path.dirname(os.path.abspath(__file__)) file_path = 'file:///' + path + '/html/form.html' self .driver.get(file_path) def test_checkbox( self ): #定位跳舞 dancing = self .driver.find_element_by_name( "dancing" ) #如果没有选择,则点击选择 if not dancing.is_selected(): dancing.click() sleep( 2 ) running = self .driver.find_element_by_name( "running" ) if not running.is_selected(): running.click() sleep( 2 ) swimming = self .driver.find_element_by_name( "swimming" ) if not swimming.is_selected(): swimming.click() sleep( 2 ) #再次点击取消选择游泳 swimming.click() sleep( 2 ) self .driver.quit() def test_radio( self ): #获得元素列表 gender = self .driver.find_elements_by_name( "gender" ) #选中性别男 gender[ 0 ].click() sleep( 2 ) # 选中性别女 gender[ 1 ].click() sleep( 2 ) self .driver.quit() if __name__ = = '__main__' : case = TestCheckBoxOrRadioBtn() case.test_checkbox() case.test_radio() |
运行结果:
![](https://img-blog.csdnimg.cn/direct/27f45c7a75aa4213a39d08ae2dcf5213.png)
最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】
![](https://img-blog.csdnimg.cn/direct/db7e3aa9e1bc4369bb1eeb59370a323b.png)
![](https://img-blog.csdnimg.cn/0edaf198db0444d19309d1de13f0b209.png)