简体   繁体   中英

Reusing “driver.webdriver” in a class

I'm a complete newb to python and selenium, so please excuse the design of the solution.

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.

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 .

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

for ex:- 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.

Thank you for the help. I used the suggestion from RemcoW and looked into using the Page Object design pattern. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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