1 #-*- coding:utf-8 -*- 2 __author__ = "carry" 3 4 from selenium import webdriver 5 from selenium.webdriver.common.by import By 6 from selenium.webdriver.common.keys import Keys 7 from selenium.webdriver.support.ui import Select 8 from selenium.common.exceptions import NoSuchAttributeException 9 import unittest,time,re10 import HTMLTestRunner #引入HTMLTestRunner11 class Baidu(unittest.TestCase):12 def setUp(self):13 self.driver = webdriver.Firefox()14 self.driver.implicitly_wait(30)15 self.base_url = "http://www.baidu.com"16 self.verificationErrors = []17 self.accept_next_alert =True18 #百度搜索用例19 def test_baidu_search(self):20 driver = self.driver21 driver.get(self.base_url+"/")22 driver.find_element_by_id("kw").send_keys("selenium")23 driver.find_element_by_id("su").click()24 time.sleep(2)25 driver.close()26 #百度设置用例27 def test_baidu_set(self):28 driver = self.driver29 #进入搜素设置页30 driver.get(self.base_url+"/gaoji/preferences.html")31 #设置每页搜索结果为50页32 m = driver.find_element_by_name("NR")33 m.find_element_by_xpath("//option[@value='50']").click()34 time.sleep(2)35 #保存设置的信息36 driver.find_element_by_xpath("/html/body/form/div/input").click()37 time.sleep(2)38 driver.switch_to_alert().accept()39 def tearDown(self):40 self.driver.quit()41 self.assertEqual([],self.verificationErrors)42 if __name__ == "__main__":43 #定义一个单元测试容器44 testunit = unittest.TestSuite()45 #将测试用例加入到测试容器中46 testunit.addTest(Baidu("test_baidu_search"))47 testunit.addTest(Baidu("test_baidu_set"))48 #定义一个报告存放路径,支持相对路径49 filename = r'D:\selenium_file\result.html'50 fp = file(filename,'wb')51 #定义测试报告52 runner = HTMLTestRunner.HTMLTestRunner(53 stream=fp,54 title=u'百度搜索测试报告',55 description=u'用例执行情况:'56 )57 #运行测试用例58 runner.run(testunit)