I'm new with Selenium. I'm using same code for the login session, when I'm writing test case for every page.

How can I stop re-entering the same code? Is there any other way to reuse code without repeating those codes for every test case in every page?


2 Answers 2


Using WebDriver, you're free to use all the features of your programming language of choice. And that gives a lot of opportunities to structure your tests in such a way as to avoid code repetition.

If you're new to Selenium, I'd skip Page Object Model until you get comfortable with WebDriver basics. Until then, I would just wrap the frequently used code into functions and put those functions into a separate library/module that you can use in your test cases.

Let's assume you're using Python and you repeat the code for logging in all the time. For the sake of simplicity, let's also assume that navigation to the login page is taken care of separately in the test cases, and that the login form elements have stable, unique IDs. In such a case, you can write a function like this:

def login(user, password):
    user_field = driver.find_element_by_id("user")
    password_field = driver.find_element_by_name("password")
    login_button = driver.find_element_by_name("log-on")


Then, whenever you need to login from a test case, you just call your function:

login("myuser", "mypassword")

This is greatly simplified, but should give you an idea.


You can use the Page object model which includes methods as well as locators and come up with a method to do the login that you can call from all your tests.

For more information on the Page Object model details see these links -

Page Object Model

Page Object using selenium

  • Downvoting for providing link without explanation.
    – dzieciou
    Commented Dec 16, 2016 at 16:30
  • Added necessary details given that it was already accepted. Commented Dec 17, 2016 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.