【问题标题】:How to create a single webdriver instance in Python?如何在 Python 中创建单个 webdriver 实例?
【发布时间】:2015-08-13 03:41:08
【问题描述】:

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

  1. 单独的 Driver.py 已设置为创建 Web 驱动程序实例
从硒导入网络驱动程序 类驱动程序: #创建一个类变量 实例 = 无 @静态方法 定义初始化(): 实例 = webdriver.Firefox() 返回实例
  1. 在框架的所有领域都使用此文件,例如:
从驱动程序导入驱动程序 类登录页面: @静态方法 def GoToURL(): Driver.Instance.get("示例网址") @静态方法 定义登录(): 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。

【问题讨论】:

  • 你也应该发布错误堆栈跟踪。
  • 他们抛出了什么错误?显然,这与您无法创建该实例无关(这是您根据标题所要求的)。听起来像是webdriver.get 方法抛出的异常。可能是您的网址格式不正确或其他原因。
  • btn-primary 是 CSS class 而不是 id
  • 我得到 AttributeError: 'NoneType' object has no attribute 'get' 作为错误消息
  • 尽可能提供html

标签: python selenium-webdriver


【解决方案1】:

我得到了我的问题的解决方案!!! 我没有在 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()

这就像一个魅力......

【讨论】:

  • 好吧,使用全局变量不应该是任何事情的正确答案:-(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多