Selenium WebDriver- WebElement.FindElements returns 比预期更多的元素

Selenium WebDriver- WebElement.FindElements returns more elements then expected

我有一个包含不同 "rows" 的图片库,其中有特定数量的 "columns"(图片)。我想创建一个方法,我可以在其中 select 基于 x,y 的特定图像。

所以我使用 pageObjects 搜索包含画廊的部分。

@FindBy(how = How.XPATH, using = "//section[@id='gallery']")
private WebElement sectionGallery;

然后,我创建了一个小方法,它将 return 此图库的所有行

public List<WebElement> getGalleryRows(){
        return sectionGallery.findElements(By.xpath("//div[@class='gallery-horizontal-row']"));
    }

这就是问题所在。我得到每个具有 xpath 表达式“//div[@class='gallery-horizontal-row']”的 Webelement,而不仅仅是 "sectiongallery" webelement 下的 webelement。

我是不是误解了这个功能? 对于下面的 HTML 源,我希望有 3 个 Webelements returned,但我得到 4.

当我对完整的 Xpath 表达式执行 Driver.FindElements 时,它 return 只有 3 个元素。

public List<WebElement> getGalleryRows(){
        return DriverManager.getDriver().findElements(By.xpath("//section[@id='gallery']//div[@class='gallery-horizontal-row']"));
    }

我的 HTML 模糊来源:

    <section data-section-title="Galerie" id="gallery">
<header>
    <h1>Galerie</h1>
</header>
<div>
    <div >  
        <div class="gallery-horizontal-row" style="height: 220px;">
            <div>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
            </div>
        </div>
        <div class="gallery-horizontal-row" style="height: 220px;">
            <div>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
            </div>
        </div>
        <div class="gallery-horizontal-row" style="height: 220px;">
            <div>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
                <article class="gallery-item"></article>
            </div>
        </div>
    </div>
</div>
</section>
<section id="other">
    ....
</section>  
<section id="other2">
    ....
</section>  
<section id="other3">
    ....
</section>  
<section data-section-title="other4" id="other4">
<header>
    <h1>Other4</h1>
</header>
<div>
    <div >  
        <div class="gallery-horizontal-row" style="height: 220px;">
            <div>
....

在第二个表达式的//descendant-or-self::轴)前面加上.

return sectionGallery.findElements(By.xpath(".//div[@class='gallery-horizontal-row']"));

Am I misinterpreting this functionality?

不完全,但以 // 开头的表达式会选择输入文档中 任意位置 的元素,即使您选择了输入的子集作为起始指向第二个表达式。尽可能避免 // - 这是一个被严重过度使用的轴 - 特别是对于 XPath 初学者。

另一方面,以.//开头的表达式实际上以上下文节点为起点。