简体   繁体   中英

How to create a loop that increments a tr by 1 with a max of 100 time using a CssSelector in C#

So basically I have a table of 100 rows on a web page, each row contains a button, I want to write a loop that will increment the tr in the CssSelector by 1 with a max of 100 times.

So far I have an extremely receptive process that works but is very costly.

Example of my code:

driver.FindElement(By.CssSelector("#Main > tbody > tr:nth-child(1) > td:nth-child(2)")).Click();
driver.FindElement(By.CssSelector("#Main > tbody > tr:nth-child(2) > td:nth-child(2)")).Click();
driver.FindElement(By.CssSelector("#Main > tbody > tr:nth-child(3) > td:nth-child(2)")).Click();

to 100...

I would like a loop to do something like this:

driver.FindElement(By.CssSelector("#Main > tbody > tr:nth-child(1)[i++] > td:nth-child(2)")).Click();

I would do a search to find all the elements that contained a 'tr' tag and then loop through those. If you want to stop at a max of 100 then you can add that to the condition of the loop

ReadOnlyCollection<IWebElement> allRows = driver.FindElements(By.CssSelector("#Main > tbody > tr")

for(int i = 0 ; i < allRows.Count && i < 100 ; i++){

  WebElement rowElements = allRows[i].FindElements(By.CssSelector("td"))

  rowElements[2].click()
}

I don't recall if I used Count or Length() on the first line for the For loop in the past. It's been a few years since I've used C#, so forgive any bad syntax, but this should do the trick. You can add in waits to make sure the elements are visible before you start searching, add a check that rowElements[2] is not null before attempting to click and you might want to wrap this in a try/catch block, too.

Use simple for loop.

string locator;
for(int i=1; i<=100; i++){
locator = "#Main > tbody > tr:nth-child("+i+") > td:nth-child(2)";
driver.FindElement(By.CssSelector(locator)).click();
}

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