gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:47:33 25 4
gpt4 key购买 nike

我有一个包含不同“行”的图片库,其中包含特定数量的“列”(图像)。我想创建一个方法,我可以根据 x,y 选择特定图像。

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

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

然后,我创建了一个小方法,它将返回此画廊的所有行
public List<WebElement> getGalleryRows(){
return sectionGallery.findElements(By.xpath("//div[@class='gallery-horizontal-row']"));
}

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

我误解了这个功能吗?
对于下面的 HTML 源代码,我希望返回 3 个 Webelement,但我得到了 4 个。

当我在完整的 Xpath 表达式上执行 Driver.FindElements 时,它只返回 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 初学者。

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

关于Selenium WebDriver- WebElement.FindElements 返回比预期更多的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29005942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com