如何在python中创建单个webdriver实例?

Pra*_*dey 1 python selenium-webdriver

我正在用python创建自动化框架,但是我却坚持创建Web驱动程序的单个实例。这是我的框架设计的摘录:

  1. 一个单独的Driver.py,它具有用于创建Web驱动程序实例的设置
从硒导入webdriver

类驱动程序:
    #创建类变量
    实例=无

        @staticmethod
        def Initialize():
            实例= webdriver.Firefox()
            返回实例
  1. 在框架的所有区域使用此文件,例如:
从驱动程序导入驱动程序

类LoginPage:
    @staticmethod
    定义GoToURL():        
        Driver.Instance.get(“样本网址”)

    @staticmethod
    def Login():
        Driver.Instance.find_element_by_id(“ session_key-login”)。send_keys(“ sample@gmail.com”)
        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_element ...正在引发错误。可能是这里没有识别Driver.Instance。

Pra*_*dey 6

我已经解决了我的问题!!!我没有在文件Driver.py中创建类变量,而是这样做的:

从硒导入webdriver

实例=无

def Initialize():
    全局实例
    实例= webdriver.Chrome(“驱动程序路径”)
    Instance.implicitly_wait(5)
    返回实例

def CloseDriver():
    全局实例
    Instance.quit()

我必须使用此实例的地方,我这样做:

导入驱动程序

类LoginPage:
    @staticmethod
    定义GoToURL():
        Driver.Instance.get(“样本网址”)

    @staticmethod
    def Login():
        Driver.Instance.find_element_by_id(“ session_key-login”)。send_keys(“样本用户名”)
        Driver.Instance.find_element_by_id(“ session_password-login”)。send_keys(“示例密码”)
        Driver.Instance.find_element_by_id(“ btn-primary”)。click()

我正在运行此测试的文件是这样的:

导入单元测试
导入驱动程序
从LoginPage导入LoginPage

类LoginTest(unittest.TestCase):
    def setUp():
        Driver.Initialize()

    def testUserCanLogin(self):
        #转到登录网址
        LoginPage.GoToURL()
        #输入用户名,密码并点击登录
        LoginPage.Login()
        #在右上角,检查是否已登录正确的用户

    def tearDown():
        Driver.CloseDriver()

这像魅力一样运作...