Search code examples
javaseleniumxpathhtmlelements

HtmlElements finds 3 elements instead of only one in block when searching with XPath


I have a block:

@Block(@FindBy(xpath = "//tr[contains(@class,'bg-success')]"))
public class ShareContentRowBlock extends HtmlElement {

   @FindBy(xpath = "//h3[@class='fileName']/span/a")
   private TextBlock contentNameText;

   public String getContentName() {
       return contentNameText.getText();
   }

   .... // some other elements and methods
}

I described a page:

public class DocumentLibraryPage extends SitePage {

    private List<ShareContentRowBlock> shareContentRowBlocks;

    .....

    public ShareContentRowBlock getShareContentRowBlock(String name){
        for (ShareContentRowBlock conentRowBlock: shareContentRowBlocks){
            if(name.equals(conentRowBlock.getContentName())){
                return conentRowBlock;
            }
        }
        return null;
    }
}

When I try to get element, it returns not exactly element that I want to see.

I have html with elements tree:

   html
       h3.fileName
         span 
             a
       h3.fileName
         span 
             a
       table.bg-success
         h3.fileName
             span 
                 a

I want to get element <a> inside table, but it returns all 3 <a> elements. When i try to debug it really finds all <a> elements with ignoring parent block xpath.

What wrong with it? Am I need to change selectors, or describe block in other way?


Solution

  • Starting xpath locator with "//" means absolute block position. In order to make relative search you should start it with ".":

    @Block(@FindBy(xpath = "//tr[contains(@class,'bg-success')]"))
    public class ShareContentRowBlock extends HtmlElement {
    
       @FindBy(xpath = ".//h3[@class='fileName']/span/a")
       private TextBlock contentNameText;
    
       public String getContentName() {
           return contentNameText.getText();
       }
    
       .... // some other elements and methods
    }