如何使用Selenium判断一个元素是否有子元素?

3

我正在使用C#通过Selenium。我使用这个XPath来获取所有子元素。

element.FindElements(By.XPath("./child::*"));

尽管在超时后如果没有子进程,它会抛出错误。我正在寻找一种简单的方法来确定它是否有子进程以避免异常。


1
FindElements不应该抛出异常,但如果没有元素存在,则使用隐式等待。 - Dakshinamurthy Karra
5个回答

3

根据您的问题,要获取一个父节点的所有子节点,您可以使用以下xpath语法结合FindElements()方法和following-sibling::*属性:

  • Sample Code Block :

    List<IWebElement> textfields = new List<IWebElement>();
    textfields = driver.FindElements(By.XPath("//desired_parent_element//following-sibling::*"));
    

    Note : When FindElements() is used inconjunction with implicitly or explicitly waits, FindElements() method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.

  • XPath Details :

    • Description : This xpath technique is used to locate the sibling elements of a particular node.
    • Explanation : The xpath expression gets the all the sibling elements of the parent element located using desired_parent_element.

2

FindElements返回一个列表,所以你可以检查列表的大小,如果为零,则表示没有子元素。

Java

List<WebElement> childs = rootWebElement.findElements(By.xpath(".//*"));
int numofChildren = childs.size();

C#

IReadOnlyList<IWebElement> childs = rootWebElement.FindElements(By.XPath(".//*"));
Int32 numofChildren = childs.Count;

0
bool HasChild(IWebElement element)
{
    //Save implicit timeout to reset it later 
    var temp = driver.Manage().Timeouts().ImplicitWait;

    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
    bool exists = element.FindElements(By.XPath(".//*")).Count > 0;
    driver.Manage().Timeouts().ImplicitWait = temp;

    return exists;
}

0

最简单的方法是:

boolean hasChildren(WebElement node) {
    return node.findElements(By.xpath("./descendant-or-self::*")).size() > 1;
}

假设您想查看是否有特定的子元素(或输入或跨度)。除了node.findElements(By.xpath("input"))之外,还有没有其他方法可以增强上述功能,如果没有任何元素,它仍将花费很长时间。 - Tony

0

Javascript中需要做的事情:

var childElements = await element.findElements(By.xpath('.//*'));
    for (i = 0; i <= childElements.length; i++) {
        var elementId = await childElements[i].getAttribute("id");
        await console.log(elementId);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接