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

前端 未结 2 1179
名媛妹妹
名媛妹妹 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:21

    I created WebElement extension, I hope useful.

    public static IWebElement GetElementParentByClass(this IWebElement element, string ClassName)
    {
        try
        {
            IWebElement parent = element;
            do
            {
                parent = parent.FindElement(By.XPath("./parent::*")); //parent relative to current element
    
            } while (!parent.GetAttribute("class").Equals(ClassName));
    
            return parent;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    

提交回复
热议问题