selenium

修改前的代码,运行时会打开多个浏览器页面(因为运行一次webdriver.Chrome(),就会打开一个页面)

修改后的代码,将webdriver.Chrome()放在配置文件的全局变量driver中,使用时import即可

1. 修改前代码:

test_base.py

 

test_baidu.py

 

2. 修改后代码:

 conf.py

from selenium import webdriver
driver = webdriver.Chrome()   # 定义一个全局变量,使用时import即可(防止运行时打开多个浏览器页面)

test_base.py

....
from conf.conf import driver  # 引入全局变量driver


class MyTestBaidu(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = driver   # 将全局变量driver赋值给cls.driver
        cls.driver.maximize_window()
        cls.driver.implicitly_wait(10)
        cls.base_url = 'http://www.baidu.com/'
        cls.page = BaiduPage(cls.driver)
....

test_baidu.py

....
from conf.conf import driver   # 引入全局变量driver


class TestSearch(MyTestBaidu):

    @Screen(driver)    # 使用全局变量driver
    def test_search_1(self):
        self.driver.get(self.base_url)
        self.page.search_input.send_keys('python')
        self.page.search_button.click()
        time.sleep(2)
        self.assertEqual(self.driver.title, 'python_百度搜索1')
        time.sleep(2)
....

   

原文地址:https://www.cnblogs.com/xiaochongc/p/12837765.html