for loop “index was out of range” c# webdriver

后端 未结 5 661
一生所求
一生所求 2021-01-16 07:08

I am getting \"index out of range\" from this loop. But I need to use new elements that loop founds, how do I do that? Please help to fix the problem

int lin         


        
5条回答
  •  悲哀的现实
    2021-01-16 07:33

    the first one gets all of your elements by tag name ...let's assume 5.

    in the loop, your driver get's all the elements by css selector, and you might have a different number here. let's say 4.

    then, you might be trying to set the fifth element in a four element array. boom.

    Easiest fix to debug:

    int linkCount = driver.FindElements(By.TagName("a")).Count;
    string[] links = new string[linkCount];
    // WRITE OUT HOM MANY links you have
    
    for (int i = 0; i < linkCount; i++)
    {
        List linksToClick = driver.FindElements(By.CssSelector("a[href]")).ToList();
        // ASSERT THAT YOU HAVE THE SAME AMOUNT HERE
        If (links.Count != linksToClick.Count)
             // your logic here
    
        links[i] = linksToClick[i].GetAttribute("href");
    }
    

提交回复
热议问题