Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

My question is regarding dynamic By Locators. My Page classes usually look like that:

public class MyPage {

    private WebDriver driver;

    private By myFixedLocator = By.xpath(".......");

    private String myDynamicLoactor = "//div[@id = 'someId']" +

                                      "//div[contains( @class, '<className>')]";

    public MyPage(WebDriver driver) {this.driver = driver;}

    public AnotherSuperPage getAnotherPage(String className) {

        By tmpBy = By.xpath(myDynamicLocator.replace("<className>", className));

        driver.findElement(tmpBy);

        return new AnotherSuperPage(driver);

    }

   //for example here: childOne and Two are sub classes of AnotherSuperClass

   public  AnotherChild1Page getChildOne() {return getAnotherPage("childOne");}

   public  AnotherChild1Page getChildTwo() {return getAnotherPage("childTwo")}

}

Locators like myDynamicLocator represent elements, they all have similar XPath structure except the one String part. Is there any better way to do this? As far as I understood, the By locators are final and immutable. This is also why I don't use Page Factory, since the @FindBy annotation I can use flexible locator as in the example above. And when I have a By locator, can I get the text inside in a smooth way? because By.toString() gives me the whole information, including "xpath".

1 Answer

0 votes
by (62.9k points)

You could have also achieved it by simply doing it as:

public AnotherSuperPage getAnotherPage(String className) { driver.findElement(By.xpath("//div[@id = 'someId']//div[contains( @class, '" + className +"')]"));

 return new AnotherSuperPage(driver); }

instead of creating a string object then replacing it and storing it in another variable, though anyhow this is what happens internally, but less coding.

Browse Categories

...