Loading...

How to find elements dynamically in selenium


Currently in my firefox driver, if I want to locate an element, I write the code as so:

WebDriver firefoxDriver = new FirefoxDriver();

...

firefoxDriver.findElement(By.id("testid")).isDisplayed();

or

firefoxDriver.findElement(By.name("testname")).isDisplayed();

or

firefoxDriver.findElement(By.class("testclass")).isDisplayed();

etc

However, I have these elements within a separate page like so:

 @FindBy(id = "testid")
    public WebElement testIdElement;

    @FindBy(name = "testname")
    public WebElement testNameElement;

   @FindBy(class = "testclass")
    public WebElement testClassElement;

I want to search my elements like the below but the below doesn't work because it expects a By:

firefoxDriver.findElement(elementsPage.testIdElement);

or

firefoxDriver.findElement(elementsPage.testNameElement);

or

firefoxDriver.findElement(elementsPage.testClassElement);

What will be the best way to tackle this scenario? I don't really want to keep hard coding the elements, instead better using the elements I have already defined in my elements list.

- - Source

Answers

answered 1 week ago Valga #1

Simple, declare them as a By like this in your pageObject:

public By testIdElement = By.id("testid");

public By testNameElement = By.name("testname");

public By testClassElement = By.className("testclass");

then call them at the findelements method the way you want to:

firefoxDriver.findElement(elementsPage.testIdElement);

firefoxDriver.findElement(elementsPage.testNameElement);

firefoxDriver.findElement(elementsPage.testClassElement);

i personally like to put the driver.findElement method in the pageObject as a lambda expression, to avoid rewriting code:

what i do on C#:

public IWebElement Test => webdriver.FindElement(By.CssSelector("test"));

converting to Java:

public WebElement test -> driver.findElement(By.cssSelector("test"));

so, writing my code would be something like this:

page.Test.Click();
page.Test.SendKeys("...");

As i don't like using elements in the Test class, i write these methods in the pageobject (separating test logic from the script), example:

    public PageObjectClassExample ShowFilters()
    {
        showFiltersButton.Click();
        return this;
    }
    public PageObjectClassExample ClearAllFilters()
    {
        finalDatePicker.Clear();
        initialDatePicker.Clear();
        searchButton.Click();
        return this;
    }
    public PageObjectClassExample HideShowIssuerColunm()
    {
        ShowHideColumnBtn.Click();
        IssuerColumnCheck.Click();
        KeyColumnCheck.Click();
        ShowHideColumnBtn.Click();
        return this;
    }

and in the Test file i would write something like this:

PageObjectClassExample page = new PageObjectClassExample();
page
    .ShowFilters()
    .ClearAllFilters()
    .HideShowIssuerColumn();

comments powered by Disqus