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

ぃ、小莉子 提交于 2019-12-08 10:39:32

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/26404866/htmlelements-finds-3-elements-instead-of-only-one-in-block-when-searching-with-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!