for循环“索引超出范围"; C#Web驱动程序 [英] for loop "index was out of range" c# webdriver

查看:94
本文介绍了for循环“索引超出范围"; C#Web驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此循环中获得索引超出范围".但是我需要使用循环发现的新元素,我该怎么做?请帮助解决问题

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 linkCount = driver.FindElements(By.CssSelector("a[href]")).Count;
string[] links = new string[linkCount];

for (int i = 0; i < linkCount; i++)
{
    List<IWebElement> linksToClick = driver.FindElements(By.CssSelector("a[href]")).ToList();
    links[i] = linksToClick[i].GetAttribute("href");
}

推荐答案

您可以重写代码以绕过for循环:

You can rewrite your code to bypass the for loop:

string[] links = driver.FindElements(By.CssSelector("a[href]")).Select(l => l.GetAttribute("href")).ToArray();

这还应该避免索引超出范围的问题,并减少您必须编写的代码量.

This should also avoid the index out of range problem, and cut down the amount of code you have to write.

这篇关于for循环“索引超出范围"; C#Web驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆