Selenium是当前主流的Web自动化测试工具。几乎到了统治地位,它也是无数其他浏览器自动化工具、API和框架中的核心技术。
import unittest
from time import sleep
from selenium import webdriver
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dr = webdriver.Chrome()
cls.base_url = "https://www.baidu.com"
@classmethod
def tearDownClass(cls):
cls.dr.close()
# 这是普通的方法
def search_keyword(self, keyword):
self.dr.find_element_by_name("wd").send_keys(keyword)
self.dr.find_element_by_id("su").click()
sleep(2)
def test_baidu_search_selenium(self):
dr = self.dr
dr.get(self.base_url)
self.search_keyword("selenium")
self.assertEqual(dr.title, "selenium_百度搜索")
def test_baidu_search_unittest(self):
dr = self.dr
dr.get(self.base_url)
self.search_keyword("unittest")
self.assertEqual(dr.title, "unittest_百度搜索")
if __name__ == '__main__':
unittest.main()