在不同情况下使用相同的浏览器会话

时间:2018-07-10 12:00:52

标签: python selenium

在下面的代码中,我试图在不同的测试用例中使用相同的浏览器会话,但是在运行其后,发现为每个测试用例打开了两个不同的浏览器会话。请指导我解决此问题:

driver1 = webdriver.Chrome(
            executable_path="C:\\Program Files (x86)\\chromedriver.exe")

class Test_Trials(unittest.TestCase):

    def test_1(self):
        driver1.set_page_load_timeout(20)
        driver1.get("http://192.168.221.238:8180/tnp/")
        driver1.maximize_window()

    def test_2(self):
        driver1.find_element_by_id("j_username").send_keys("admin")
        driver1.find_element_by_name("j_password").send_keys("admin1001")
        driver1.find_element_by_class_name("gwt-Button").click()
        driver1.set_page_load_timeout(20)

2 个答案:

答案 0 :(得分:1)

尝试在模块设置中使用pytest,在执行类之前初始化驱动程序:

class Test_Trials(unittest.TestCase):

  def setup_module(module):
      driver1 = webdriver.Chrome(
          executable_path="C:\\Program Files (x86)\\chromedriver.exe")

或类方法:

 @classmethod
 def setup_class(cls):
      driver1 = webdriver.Chrome(
          executable_path="C:\\Program Files (x86)\\chromedriver.exe")

完整文档:https://docs.pytest.org/en/latest/xunit_setup.html

答案 1 :(得分:0)

尝试在类中声明和初始化driver1。或者,仅在类内部声明它(用None初始化),然后在setupClass方法中将其初始化,如下所示:

@classmethod
def setUpClass(cls):
    driver1 = webdriver.Chrome(
        executable_path="C:\\Program Files (x86)\\chromedriver.exe")