python+selenium2自动化---CheckBox和radiobutton定位
Posted 小江子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()
以上是关于python+selenium2自动化---CheckBox和radiobutton定位的主要内容,如果未能解决你的问题,请参考以下文章
Selenium2+python自动化2-pip降级selenium3.0
Selenium2+python自动化2-pip降级selenium3.0
Selenium2+python自动化2-pip降级selenium3.0