How to find all parent elements using Selenium C# WebDriver?

前端 未结 2 1165
名媛妹妹
名媛妹妹 2020-12-21 00:42

I have a variable that is a By class. I wish to call FindElements to return the corresponding element as well as all of the parent elements of this

2条回答
  •  醉梦人生
    2020-12-21 01:32

    If I understand your question correctly you want to find the By element and then the parents up until the root.

    You can just use XPath to get the parent element until you get to the page root. So something like this:

    public ReadOnlyCollection FindElementTree(By by)
    {
        List tree = new List();
    
        try
        {
            IWebElement element = this.driver.FindElement(by);
            tree.Add(element); //starting element
    
            do
            {
                element = element.FindElement(By.XPath("./parent::*")); //parent relative to current element
                tree.Add(element);
    
            } while (element.TagName != "html");
        }
        catch (NoSuchElementException)
        {
        }
    
        return new ReadOnlyCollection(tree);
    }
    

    Optionally you can stop on the body element instead of the html one.

    Also note that this is fairly slow, especially if its a deeply nested element. A faster alternative would be to use ExecuteScript to run a javascript snippet that uses the same logic and then returns all the elements at once.

提交回复
热议问题