示例:对 form.html 中的复选框和单选按钮进行操作
    image.png

    注:form.html 和 demo03.py 在同一目录下
    form.html 代码如下

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>测试 checkbox 和 radio button</title>
    6. </head>
    7. <body>
    8. <form action="javascript:alert('test')">
    9. apple: <input type="checkbox" name="apple" value="apple"><br>
    10. banana: <input type="checkbox" name="banana" value="banana"><br>
    11. mango: <input type="checkbox" name="mango" value="mango"><br>
    12. <hr>
    13. gender: <input type="radio" name="gender" value="male">male
    14. <input type="radio" name="gender" value="male">female<br>
    15. <input type="submit" value="submit">
    16. </form>
    17. </body>
    18. </html>

    demo03.py 代码如下

    1. from selenium import webdriver
    2. from time import sleep
    3. from os import path
    4. from os.path import join
    5. class TestCase(object):
    6. def __init__(self):
    7. demo03_path = path.dirname(path.abspath(__file__))
    8. form_path = join(demo03_path, 'form.html')
    9. self.driver = webdriver.Chrome()
    10. self.driver.maximize_window()
    11. self.driver.get(form_path)
    12. def test_checkbox(self):
    13. """
    14. 测试 checkbox 的方法
    15. :return:
    16. """
    17. apple = self.driver.find_element_by_name('apple')
    18. if not apple.is_selected():
    19. apple.click()
    20. banana = self.driver.find_element_by_name('banana')
    21. if not banana.is_selected():
    22. banana.click()
    23. sleep(2)
    24. def test_radio_button(self):
    25. """
    26. 测试 radio 的方法
    27. :return:
    28. """
    29. self.driver.find_elements_by_name('gender')[1].click()
    30. if __name__ == '__main__':
    31. case = TestCase()
    32. case.test_checkbox()
    33. case.test_radio_button()