Skip to main content
 首页 » 编程设计

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

2025年05月04日46小虾米

我正在用 Python 创建一个自动化框架,但我在创建 Web 驱动程序的单个实例时遇到了困难。 这是我的框架设计的摘录:

  1. 一个单独的 Driver.py,用于创建网络驱动程序实例
from selenium import webdriver 
 
class Driver: 
    #creating a class variable 
    Instance = None 
 
        @staticmethod 
        def Initialize(): 
            Instance = webdriver.Firefox() 
            return Instance 
  1. 在框架的所有领域使用此文件,例如:
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("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。

请您参考如下方法:

我找到了问题的答案!!! 我没有在文件 Driver.py 中创建类变量,而是这样做了:

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() 

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

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() 

我运行这个测试的文件是这样的:

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() 

这就像一个魅力...