简体   繁体   中英

System.ArgumentOutOfRangeException: Index was out of range Error in C#

I was writing a file download program from the inte.net with Selenium. But a few seconds after the program is started, I encounter this error.

        Thread.Sleep(500);
        var driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://oblivious212.artstation.com/");
        Thread.Sleep(1000);
        var Projects = driver.FindElements(By.ClassName("album-grid-item"));
        for(int i = 0; i < Projects.Count(); i++)
        {
            Projects = driver.FindElements(By.ClassName("album-grid-item"));
            Projects[i].Click();
            Thread.Sleep(1000);
            var Images = driver.FindElements(By.TagName("img"));

            for(int x = 0; x < Images.Count(); x++)
            {
                var ImageUrl = Images[x].GetAttribute("src");
                var ImageName = Images[x].GetAttribute("alt");
                WebClient Downloader = new WebClient();
                Downloader.DownloadFile(ImageUrl, "C:\\Users\\DeLL\\Pictures\\Images\\" + ImageName + ".jpg");
            }
            Thread.Sleep(250);
            driver.Navigate().Back();

Fault point.

The variable Projects is already set outside the for loop. You do not have to get it again and again inside the loop. Also, you are iterating on its count and modifying the object you iterate on would give an exception inside a 'foreach' loop, in a for loop it also bad practice.

You can anyways check if the index is valid anyways in a condition.

if (Projects.ElementAt(i) == null) {
 continue; //index i is wrong - continue will propagate to next element in your for loop
}

Note that the ElementAt method needs to have the namespace System.Linq added to your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM