Home > OS >  How to define driver in pytest
How to define driver in pytest

Time:08-25

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

CodePudding user response:

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

CodePudding user response:

Download the driver of the website and add it into Sytem PATH.

Tha use pip install selenium to download the python moudle.

And this is the example code.

from selenium import webdriver

driver = webdriver.Chrome()

Then when you want to you it, just use driver.XXX(XXX means to order)

  • Related