简体   繁体   English

在类中重用“ driver.webdriver”

[英]Reusing “driver.webdriver” in a class

I'm a complete newb to python and selenium, so please excuse the design of the solution. 我对python和selenium完全陌生,因此请原谅该解决方案的设计。

I've been looking around a lot, but I can't find the answer I need. 我已经四处逛逛,但是找不到所需的答案。

I'm trying to create a class called "Navigators" , which I can use to easily to navigate round a system. 我正在尝试创建一个名为“ Navigators”的类,该类可用于轻松地在系统中导航。

The idea would be that I can call a function from the class, which will then take me to the window that I want to work on. 我的想法是,我可以从类中调用一个函数,然后将其带到我要处理的窗口。

The problem I'm facing is with the driver variable 我面临的问题是驱动程序变量

driver = webdriver.Chrome('C:/temp/chromedriver.exe')

Every time I use the variable, it opens a new Chrome browser . 每次使用该变量时,它都会打开一个新的Chrome browser

Is there a way for me to use the variable without opening a new browser? 有没有一种方法可以使用我的变量而不打开新的浏览器? I'd like my function to do something like: 我希望我的功能可以执行以下操作:

Users = driver.find_element_by_link_text("Users")
Users.click()

You will have to create single instance of driver. 您将必须创建驱动程序的单个实例。

class commonLib{
 Webdriver driver = null
 private setDriver()
{
    driver = new FirefoxDriver();
}
public static getDriver(){
  return driver;
}
}

So, whereever you need to use the driver. 因此,无论您在哪里使用驱动程序。 make use of function getDriver(); 利用功能getDriver();

for ex:- Users=getDriver().find_element_by_link_text("Users") Users.click() 例如: Users=getDriver().find_element_by_link_text("Users") Users.click()

Also, you can make use of Singleton classes for webdriver class where only one instance is created no matter how many instances you create, it will be pointing to single instance. 另外,您可以将Singleton类用于webdriver类,其中无论创建多少实例,都只会创建一个实例,它将指向单个实例。

Thank you for the help. 感谢您的帮助。 I used the suggestion from RemcoW and looked into using the Page Object design pattern. 我使用了RemcoW的建议,并研究了使用Page Object设计模式。 It seems to be the best fit for what I'm trying to achieve, here's the page that I used to base my code on: 这似乎最适合我要实现的目标,这是我用来建立代码的页面:

https://justin.abrah.ms/python/selenium-page-object-pattern--the-key-to-maintainable-tests.html https://justin.abrah.ms/python/selenium-page-object-pattern--the-key-to-maintainable-tests.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM