一尘不染

了解WebElement.findElement()和XPATH

selenium

我想使用WebElement.findElement()API使用XPATH在父节点内定位一个节点//span[@class='child- class']。我以为这会让我回到<div>父母那边。但是,它将返回我在整个DOM树中找到的第一个。我使用了错误的XPATH吗?

我也曾尝试使用.//span[@class='child-class']XPATH,但这确实会返回任何东西。

谢谢。

更新:

给定下面的HTML,我想为子标题<span>和子日期定义一个定位器,<span>并使用WebElement.findElement()API对其进行定位,而不管父级是“
// a / li [1]”还是“ // a” / li [2]“

<a>
    <li> parent 1
        <div>
            <span class="child-title child-style">title 1</span>
            <span class="child-date child-style"> date 1</span>
            <span class="child-author">author 1</span>
        </div>
    </li>
</a>
<a>
    <li> parent 2
        <div>
            <span class="child-title child-style">title 2</span>
            <span class="child-date child-style"> date 2</span>
            <span class="child-author">author 3</span>
        </div>
    </li>
</a>
<a>
    <li> parent 3
        <div>
            <span class="child-title child-style">title 3</span>
            <span class="child-date child-style"> date 3</span>
            <span class="child-author">author 3</span>
        </div>
    </li>
</a>

我有一个WebElement parent2初始化,并使用位于"//a/li[2]"

WebElement child = parent2.findElement(By.xpath("//span[@class='child- author']")); 会给我“作者1”

WebElement child = parent2.findElement(By.xpath("span[@class='child- author']")); 会给我 NoSuchElementException


阅读 559

收藏
2020-06-26

共1个答案

一尘不染

我的示例代码有2条评论

1-使用您发布的HTML,找不到xpath // a / li [2](我们只有3个元素带有// a / li [1])

2-假设我们有正确的代码,则需要了解Xpath中单斜杠和双斜杠之间的区别

a/b (single slash): select element that has "tag b" and "stands right after" an element that has "a tag"

例如:

<a>
    <b>
          <d>
               <c>
               </c>
          </d>
    </b>
</a>

a//b (double slash): select element that has "tag b" and is n-level-child an element that has "a tag"

例如:

<a>
    <c>
          <d>
               <b>
               </b>
          </d>
    </c>
</a>

所以,用你的代码

<a>
<li> parent 1
    <div>
        <span class="child-title child-style">title 1</span>
        <span class="child-date child-style"> date 1</span>
        <span class="child-author">author 1</span>
    </div>
</li>
</a>

如果要获取日期信息,应使用

WebElement parent = driver.findElement(By.xpath("//a/li"));
WebElement date = parent.findElement(By.xpath("div/span[contains(@class, 'child-date')]"));
WebElement date = parent.findElement(By.xpath("//span[contains(@class, 'child-date')]"));

代码

WebElement date = parent.findElement(By.xpath("span[contains(@class, 'child-date')]"));

将带出NoSuchElementException,因为[li]标签之后没有[span]标签

希望帮助

2020-06-26