0

I'm new to python selenium tests and, after Java C# projects, I'm a little bit confused. Before I set up a driver I need to define it with some Type, for example in Java:

static WebDriver driver;
if ('Chrome') {
    driver = ...
} else {
    driver = ...
}

How can I define driver in python and how other classes can access it without driver instance creation? Thanks

Darkproduct
  • 1,062
  • 13
  • 28
Arsenium
  • 3
  • 2
  • Have a look at the documentation here: https://www.selenium.dev/documentation/webdriver/getting_started/open_browser/ – Darkproduct Aug 24 '22 at 11:27
  • Thanks for your reply, but I still don't understand how can I define a cross-browser driver...(as in the question) in python it can't be static. In the start I want it to be None and after this, I define it as Chrome or FF, etc. And because the driver is not static I can't understand how other classes can access it. Thanks – Arsenium Aug 24 '22 at 11:56
  • See https://stackoverflow.com/questions/17540971/how-to-use-selenium-with-python – lubo Aug 24 '22 at 11:59
  • You can use a member variable that is initialized in the constructor. Or you can wrap the WebDriver with your own wrapper classes for different browsers. There is a multitude of solutions and it depends on what else you want to do, to know which solution is best. – Darkproduct Aug 24 '22 at 12:06

1 Answers1

0

It works the same in python as it does in Java/C#. Once you have your driver variable instantiated with the desired browser, you just pass the driver instance to a new class/page object.

Your test would look like

driver = webdriver.Chrome() # or whatever browser driver you want
driver.get("https://www.website.com")
...
homePage = HomePage(driver)
assert homePage.get_username() == "John Smith"

and then you define your HomePage class

class HomePage()
    USERNAME_LOCATOR = (By.ID, 'username')

    def __init__(self, driver):
        self.driver = driver

    def get_username(self):
        return self.driver.find_element(USERNAME_LOCATOR).text
JeffC
  • 22,180
  • 5
  • 32
  • 55