如何查找特定WebElement的子元素(我不知道xpath)

时间:2017-07-18 18:47:48

标签: java selenium xpath selenium-webdriver

我有一个具有唯一类名的任意数量的tile。其中一个有一个独特的标题,所以我试图专门抓住那个。一旦我完成了这项工作,我希望在其结构中更深入地引用子元素。

" tile。" tile.findElement()的一部分在这里为我做什么?我想专门使用相对于tile的xpath。

public WebElement getArticleTileByTitle(String title){
        By xpath = By.xpath(".//div[contains(., '" + title + "') or @title='" + title +  "']");
        List<WebElement> tiles = findPresentElements(By.className("articleTile"));
        for(WebElement tile : tiles){
            if(isElementPresent(tile, xpath))
                return tile;
        }
        return null;
    }

public boolean articleTileImageIsVisible(WebElement tile){
    WebElement background = tile.findElement(By.xpath("/*[2]/*[2]/*[1]/*[3]")); //This throws NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/*[2]/*[2]/*[1]/*[3]"}
    //figure out stuff about background
}

我知道背景属于img类型,所以我已经尝试了

tile.findElement(By.xpath("./img/*[2]/*[2]/*[1]/*[3]"));
tile.findElement(By.xpath("./*/*[2]/*[2]/*[1]/*[3]"));
tile.findElement(By.xpath(".//*/*[2]/*[2]/*[1]/*[3]"));
tile.findElement(By.xpath("./*/*[2]/*[2]/*[1]/*[3]"));

从不如此,我不断在NoSuchElementException上获得变化:没有这样的元素:无法找到元素:{&#34;方法&#34;:&#34; xpath&#34;,&#34;选择器&#34; :&#34; / [2] / [2] / [1] / [3]&#34;}并且这不是有效的xpath

这个问题与Selenium 2 - Can findElement(By.xpath) be scoped to a particular element?非常相似,但人们似乎误解了它或者我的用例不同。

2 个答案:

答案 0 :(得分:1)

findElements()的{​​{3}}说:

  

使用xpath时请注意webdriver遵循标准约定:以“//”为前缀的搜索将搜索整个文档,而不仅仅是当前节点的子节点。使用“.//”将搜索范围限制为此WebElement的子项。

所以你应该能够做到这样的事情:

WebElement foo = driver.findElement(By.xpath("//*[@title='" + title + "']"));
WebElement bar = foo.findElement(By.xpath(".//img"));

第二个xpath中的前导点完全不同,因为它只会搜索foo的子元素。

答案 1 :(得分:0)

有类似问题的话题! - XPath to get all child nodes (elements, comments, and text) without parent

该主题的这一部分可能会让您感兴趣。

<块引用>

child::* 选择所有元素 上下文节点的子节点

child::text() 选择所有文本节点 上下文节点的子节点

child::node() 选择所有 上下文节点的子节点,无论 他们的节点类型

我们可以从父节点中识别子节点,方法是将其与父节点一起定位,然后将 ( ./child::*) 作为参数传递给 findElements(By.xpath(""))

var childs = parent.findElements(By.xpath("./child::*"));

然后在您的代码中过滤/处理它们...

相关问题