seleniumselenium-webdrivercss-selectorscucumberpageobjects

How to identify a particular Page Object fragment member element through Selenium


In our project we have multiple selenium tests run with cucumber which are testing specific components. One of these components are two identifiers, which we call country identifier and site identifier. These have the following HTML:

<div class="identifiers">   
    <div class="country-identifier">
        <span class="ident-label">
            Germany
        </span>
    </div>
    <div class="site-identifier">
        <span class="ident-label">
            Gaming
        </span>
    </div>
</div>

Now our tests have two models, one for each identifier:

@PageObject(css = "div.country-identifier")
@Named("CountryIdentifier")
@ScenarioScoped
public class CountryIdentifier {

    @Inject
    @CurrentScope
    private WebElement scope;

    @FindBy(className = "ident-label")
    @CacheLookup
    private WebElement label;

}

And:

@PageObject(css = "div.site-identifier")
@Named("SiteIdentifier")
@ScenarioScoped
public class SiteIdentifier {

    @Inject
    @CurrentScope
    private WebElement scope;

    @FindBy(className = "ident-label")
    @CacheLookup
    private WebElement label;

}

Now the problem is when I want to access the label of the site identifier the WebElement label is having the value Germany and not Gaming. This is because the css selector to get the value is apparently only applying the class name ident-label without taking into account the container class. I would expect the selector generated to find the label is combining the css defined for the page object with the selector in the @FindBy annotation. Is there a way to tell the web driver to find the element by class name only in the scope of the container specified in the css selector of the @PageObject annotation? Or do I need the full css selector in the FindBy annotation like:

@FindBy(css = "div.site-identifier .ident-label")

And

@FindBy(css = "div.country-identifier .ident-label")

Solution

  • Seems you were almost there. You can use the following locators to identify the respective elements:


    Update

    As per your comment update as you asked about it is possible to only specify ".ident-label" and make the driver search only inside the container specified by the css of page object annotation, the answer is No. That's because the class ident-label is present under both the <div> tags as follows:

    So, WebDriver instance can't distinguish them and will always pick up the first match as per the prevailing HTML DOM.


    Solution

    There can be two solution as follows:

    The first approach is the best approach and followed mostly.