gpt4 book ai didi

python - Selenium 中的单例实现 [Python]

转载 作者:行者123 更新时间:2023-12-02 19:49:09 25 4
gpt4 key购买 nike

我正在尝试使用带有 Selenium 和 Behave 的单例模式进行项目,但它无法正常工作 - 对象总是在 @then 装饰器下第二次创建。我想我在 new 方法中犯了一些错误,但无法真正看到哪里。

class WebDriver:
singleton_instance = None
driver = None

def __init__(self):
self.driver = webdriver.Chrome("C:\webdriver\chromedriver.exe")



def __new__(cls):
if not hasattr(cls, 'instance'):
cls.singleton_instance = super(WebDriver, cls).__new__(cls)
return cls.singleton_instance

@given ("website '{url}'")
def website_opener(context,url):
driver = WebDriver()
print(driver.singleton_instance)

@then("push button with text '{text}'")
def button_pusher(context,text):
driver = WebDriver() #another object of WebDriver() is created
print(driver.singleton_instance)

WebDriverWait(driver,120).until(
EC.element_to_be_clickable((By.XPATH,'//*[contains(text(), "%s")]' % text))
)

context.browser.quit()

最佳答案

您不需要使用__new__

class WebDriver:

class __WebDriver:
def __init__(self):
self.driver = webdriver.Chrome(r'C:\webdriver\chromedriver.exe')

driver = None

def __init__(self):
if not self.driver:
WebDriver.driver = WebDriver.__WebDriver().driver


@given ("website '{url}'")
def website_opener(context,url):
driver = WebDriver().driver
driver.get('https://google.com')

关于python - Selenium 中的单例实现 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58604529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com