我一直在努力解决我面临的问题,但我的想法已经用完,所以我需要帮助。
我有一个非常简单的页面:
╔════════════════════════════╦═══════════════════════════════════════╗
║ RoleName ║ Delete ║
╠════════════════════════════╬═══════════════════════════════════════╣
║ ABC1 (index starts with 1) ║ [delete button] (index starts with 0) ║
║ ABC2 ║ [delete button] ║
║ ABC3 ║ [delete button] ║
║ ABC4 ║ [delete button] ║
║ ABC5 ║ [delete button] ║
╚════════════════════════════╩═══════════════════════════════════════╝
以下是使其自动化的代码:
//count how many rows avaiable
IList<IWebElement> count = driver.FindElements(By.CssSelector("div#ctl00_MainContent_divUserInfo"));
//note: starting with 1 since the RoleName colum starts with 1 (html code render on the page)
for (int i = 1; i <= count.Count; i++)
{
string selName = string.Empty;
selName = String.Format("div#ctl00_MainContent_divUserInfo tr.item:nth-of-type({0}) > td a#aDetail:nth-child(1)", i);
string selNameText = TextByCssSelector(selName);
bool isNameExists = Names.Any(s => selNameText.Equals(s.Value.ToString(), StringComparison.OrdinalIgnoreCase));
if (isNameExists)
{
//if found then click on delete button to remove the item....
}
}
上面的代码正如我所希望的那样工作,但是存在一个问题,问题是如果我删除行而不是发生以下事情:
但请记住我仍然在for-loop
,所以我的计数是基于之前的(在删除行之前)我的问题是:
我应该如何应对这种情况?
答案 0 :(得分:3)
以相反的顺序运行循环:
for (int i = count.Count; i > 0; i--) { ... }
答案 1 :(得分:3)
由于你基本上想要删除所有行,直到没有留下来删除为什么不重写你的循环以考虑到这一点:
string selName = "//div[@id='ctl00_MainContent_divUserInfo']//tr[contains(@class, 'item')]/td//a[@id='aDetail'][1]";
while(driver.FindElements(By.CssSelector("div#ctl00_MainContent_divUserInfo")).Count > 0){
string selNameText = TextByCssSelector(selName);
bool isNameExists = Names.Any(s => selNameText.Equals(s.Value.ToString(), StringComparison.OrdinalIgnoreCase));
if (isNameExists)
{
//if found then click on delete button to remove the item....
}
}