java - 使用 XPath 搜索时,HtmlElements 在 block 中找到 3 个元素,而不是仅 1 个

标签 java selenium xpath htmlelements

我有一个 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
}

我描述了一个页面:

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;
    }
}

当我尝试获取元素时,它返回的元素并不完全是我想要查看的元素。

我有带有元素树的 html:

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

我想获取元素<a>在表内,但它返回所有 3 <a>元素。 当我尝试调试时,它确实找到了所有 <a>忽略父 block xpath 的元素。

这有什么问题吗?我是否需要更改选择器,或以其他方式描述 block ?

最佳答案

以“//”开头的xpath定位器表示绝对 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
}

关于java - 使用 XPath 搜索时,HtmlElements 在 block 中找到 3 个元素,而不是仅 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26404866/

相关文章:

python - 无法从 zillow 网站上删除某些元素

sql - 使用 t-SQL 检索 XML 元素名称

ruby - XPath 查找所有后续 sibling ,直到特定类型的下一个 sibling

java - 在Java中设置内部数组的大小

java - 为什么 Firebase 数据库上的循环会一次又一次地添加数据?

java - 在 Java 中使用 Lambda 函数的 AWS S3 事件通知

java - org.openqa.selenium.WebDriverException : java.net.ConnectException:无法使用 IEDriverServer 连接到本地主机错误

javascript - Protractor 点击问题

java - Spring 安全 SAML : Accept only signed SAML response messages from IDP

loops - 无法遍历包含XPath的文件