简体   繁体   English

System.ArgumentOutOfRangeException:索引超出范围 C# 中的错误

[英]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.我正在用Selenium写一个从inte.net下载文件的程序。但是在程序启动几秒钟后,我遇到了这个错误。

        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.变量 Projects 已在 for 循环外设置。 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.此外,您正在迭代它的计数并修改您迭代的 object 会在“foreach”循环内给出异常,在 for 循环中它也是不好的做法。

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.请注意,ElementAt 方法需要将命名空间 System.Linq 添加到您的代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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