如何使用Selenium C#WebDriver查找所有父元素?

cm0*_*007 4 selenium selenium-webdriver

我有一个By类的变量.我想调用FindElements返回相应的元素以及它的所有父元素By.我该怎么做呢?

pre*_*sto 6

如果我正确地理解了你的问题,你想要找到该By元素,然后找到父母直到根.

您可以使用XPath获取父元素,直到到达页面根目录.所以像这样:

public ReadOnlyCollection<IWebElement> FindElementTree(By by)
{
    List<IWebElement> tree = new List<IWebElement>();

    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<IWebElement>(tree);
}
Run Code Online (Sandbox Code Playgroud)

您可以选择停止body元素而不是元素html.

另请注意,这是相当慢的,特别是如果它是一个深层嵌套的元素.更快的替代方法是使用ExecuteScript运行使用相同逻辑的javascript代码段,然后立即返回所有元素.