How to create a single webdriver instance in python?
我正在用Python创建一个自动化框架,但是我在创建一个单独的Web驱动程序实例时遇到了困难。以下是我的框架设计摘录:
1 2 3 4 5 6 7 8 9 10 | from selenium import webdriver class Driver: #creating a class variable Instance = None @staticmethod def Initialize(): Instance = webdriver.Firefox() return Instance |
1 2 3 4 5 6 7 8 9 10 11 12 | from Driver import Driver class LoginPage: @staticmethod def GoToURL(): Driver.Instance.get("sample url") @staticmethod def Login(): Driver.Instance.find_element_by_id("session_key-login").send_keys("[email protected]") Driver.Instance.find_element_by_id("session_password-login").send_keys("sample_password") Driver.Instance.find_element_by_id("btn-primary").click() |
问题是driver.instance.get()或是driver.instance.find元素…正在引发错误。可能,它没有识别驱动程序.instance。
我找到了我问题的答案!!!!我没有在driver.py文件中创建类变量,而是这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 | from selenium import webdriver Instance = None def Initialize(): global Instance Instance = webdriver.Chrome("driver path") Instance.implicitly_wait(5) return Instance def CloseDriver(): global Instance Instance.quit() |
在必须使用此实例的位置,我执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 | import Driver class LoginPage: @staticmethod def GoToURL(): Driver.Instance.get("sample url") @staticmethod def Login(): Driver.Instance.find_element_by_id("session_key-login").send_keys("sample username") Driver.Instance.find_element_by_id("session_password-login").send_keys("sample password") Driver.Instance.find_element_by_id("btn-primary").click() |
运行此测试的文件是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import unittest import Driver from LoginPage import LoginPage class LoginTest(unittest.TestCase): def setUp(self): Driver.Initialize() def testUserCanLogin(self): #Go to the login url LoginPage.GoToURL() #Enter username, password and hit sign in LoginPage.Login() #On the top right corner, check that correct user has logged in def tearDown(self): Driver.CloseDriver() |
这真是一种魅力…