Selenium: get children of a IWebElement

15 Views Asked by At

I'm using selenium webdriver 4.17, with chromedriver 121.0 on a .net 6.0 test application.

I am trying to access the children of a Selenium IWebElement, but somehow it always seems to be empty. I am trying to investigate the drop down menu while hovering over a certain point. In the browser I can see the menu open, so I asume the driver should be able to find them as well, but i end op getting an empty array using the FindElements function

I've used the following code:

// initiate chrome webdriver
public IWebDriver GetChromeDriver()
{
    var driverLaunchSettings = new List<string>
    {
        "--headless", // Run in headless mode, i.e., without a UI or display server dependencies.
        "--disable-gpu", // Disables GPU hardware acceleration. If software renderer is not in place, then the GPU process won't launch
        "--no-first-run", // Skip First Run tasks, whether or not it's actually the First Run, and the What's New page
        "--no-default-browser-check", // Disables the default browser check
        "--ignore-certificate-errors", // unknown, is possibly to ignore certificate errors
        "--no-sandbox", // Disables the sandbox for all process types that are normally sandboxed.
        "--icognito", // opens in icognito mode
        "--window-size=1920,1080", // sets the window size to 1920, 1080
        "--start-maximized", // starts the browser maximised 
        "--disable-dev-shm-usage" // prevents chrome crashes in log memory vm environments
    };

    var options = new ChromeOptions();
    options.AcceptInsecureCertificates = true;
    options.AddArguments(driverLaunchSettings);
    var chromeDriver = new ChromeDriver(options);
    return chromeDriver;
}

public void SomeSadFailingUnitTest()
{
    var driver = GetChromeDriver();
    var menutoHoverOver = driver.FindElement(By.LinkText("HoveroverMe"));
    var action = new Actions(driver);
    action.MoveToElement(menutoHoverOver);
    var divWithAnchors =  driver.FindElement(By.Id("menuId"))
    // this ends up to be an empty collection
    var childElements = divWithAnchors.FindElements(By.TagName("a"));
    // I also tried this
    var childElements2 = divWithAnchors.FindElements(By.ClassName("someclass"));
    // and this, but it returns all anchors, not just the ones in the div
    var childElements3 = divWithAnchors.FindElements(By.XPath("//a[@class='someclass']"));
}

The div with id menuId looks like this:

<div id=menuId">
  <a class="someclass">link1</a>
  <a class="someclass">link2</a>
  <a class="someclass">link3</a>
</div>

I can get the information with the following xpath:

//div[@id='menuId']//a[@class='someclass']

But i want to test for visibility as well. I'm baffled that my original approach doesn't work.

0

There are 0 best solutions below