Selenium: IDE录制脚本UnitTest框架示例

  1. 打开Selenium IDE录制功能
  2. 完成一次简单的网页操作步骤
  3. 将录制生成的脚本回放调试成功
  4. 将脚本导出为python2webdriver,得到如下代码
  5. 简单阅读后添加了几句关键注释
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class STRegister(unittest.TestCase):
#继承unittest作为框架
    def setUp(self):
    #初始参数
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://192.168.1.80/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_prac1_register(self):
    #测试脚本
        driver = self.driver
        driver.get(self.base_url + "/iwebshop/")
        driver.find_element_by_link_text(u"免费注册").click()
        driver.find_element_by_name("email").clear()
        driver.find_element_by_name("email").send_keys("test")
        driver.find_element_by_name("username").click()
        driver.find_element_by_name("username").clear()
        driver.find_element_by_name("username").send_keys("test")
        driver.find_element_by_name("password").clear()
        driver.find_element_by_name("password").send_keys("123123")
        driver.find_element_by_name("repassword").clear()
        driver.find_element_by_name("repassword").send_keys("123213")
        driver.find_element_by_css_selector("input.submit_reg.current").click()

    def is_element_present(self, how, what):
    #可以用来做测试成功与失败的分支处理
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e: return False
        return True

    def is_alert_present(self):
    #判断是否有弹窗
        try: self.driver.switch_to_alert()
        except NoAlertPresentException as e: return False
        return True

    def close_alert_and_get_its_text(self):
    #获取弹窗的文字信息
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
    #收尾规范
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()