Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebDriver / Read elements into variables and re-use them

Tags:

selenium

I have a big issue With Webdriver (Selenium 2).

In my test code, I find all the elements in the beginning of my test, and do some actions on them (like click(), checking attributes, etc.). My problem is that my page is refreshed and re-load my elements, and Webdriver don't know to recognize the elements again.

I know that I can find my elements again, but in some functions I don't know my XPath/ids, and I get just the WebElements, not XPath/IDs.

Am I right in saying that it's no possible to read elements into variables and re-use them?

like image 455
Or Smith Avatar asked Dec 03 '25 22:12

Or Smith


1 Answers

WebElement element = driver.findElement(By.id("xyz"));

The above line will store the element object in the element variable. You can certainly pass this element to other functions to make use of it over there.

We generally follow the page object design pattern where we create all objects of a page as members of a class and instantiate them at once. This way we can use them anywhere in our project. For example all objects in the login page will be created as public static variables in a class called LoginPage. The constructor of LoginPage class will find elements and store them.

Next time anywhere you want to access an object of LoginPage, we access them as below (assuming that you have created elements userName and submit)...

LoginPage.userName.sendKeys("buddha");
LoginPage.submit.click();

However, as Robbie mentioned there is a chance for these objects to become inaccessible using the previously created object after a page refresh. You can use the below modified approach for ensuring these objects are always found.

Instead of creating the objects as a member variable, create a get method for each object that you may need to use.

class LoginPage
{
    public static WebElement getUserName()
    {
         return driver.findElement(By.id("xyz"));
    }
}

Once LoginPage is defined that way, next time you want to use userName, you can use the below syntax. This way you don't have to give locators to the functions that need to use these objects.

LoginPage.getUserName().sendKeys("buddha");

By using this approach, you can ensure that the objects are always accessible.

like image 169
Buddha Avatar answered Dec 07 '25 18:12

Buddha