Selenium findElements() 多次返回第一个元素的同一实例

Mic*_*ael 3 java selenium selenium-webdriver

我需要获取所有文章标题的列表。但由于某种原因,Selenium 返回了文章 WebElement 的同一实例 3 次。网页 HTML 如下所示:

<div id="content" class="site-content clearfix">
<div class="container clearfix">
    <div id="primary" class="content-area">
        <main id="main" class="site-main" role="main">
            <article id="post-403">
                <h2 class="entry-title">
                    <i class="trusted-entry-icon"/>
                        <a href="https://www.example.com/title-of-article-1/" rel="bookmark">Title of Article 1</a>
                </h2>
            </article>
            <article id="post-404">
                <h2 class="entry-title">
                    <i class="trusted-entry-icon"/>
                        <a href="https://www.example.com/title-of-article-2/" rel="bookmark">Title of Article 2</a>
                </h2>
            </article>
            <article id="post-405">
                <h2 class="entry-title">
                    <i class="trusted-entry-icon"/>
                        <a href="https://www.example.com/title-of-article-3/" rel="bookmark">Title of Article 3</a>
                </h2>
            </article>
        </main>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是Java代码:

List<WebElement> articles = driver.findElements(By.xpath("//article"));
int numberOfArticles = articles.size();
System.out.println("numberOfArticles = " + numberOfArticles);

for (WebElement article : articles){
  String articleTitle = article.findElement(By.xpath("//h2/a")).getText();
  System.out.println(articleTitle);
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

numberOfArticles = 3
Title of Article 1
Title of Article 1
Title of Article 1
Run Code Online (Sandbox Code Playgroud)

您能帮助理解这个问题吗?

Jim*_*ans 9

循环中的 XPathfor用于//查找子元素。这指示 XPath 引擎从文档的根开始搜索元素,而不是从元素开始。将循环中的 find 更改为以下内容:

\n\n
String articleTitle = article.findElement(By.xpath(".//h2/a")).getText();\n
Run Code Online (Sandbox Code Playgroud)\n\n

仔细注意.前面的//. 这告诉 XPath 引擎在其结果中仅包含当前(或 \xe2\x80\x9ccontext\xe2\x80\x9d)节点的子节点。

\n