C# how to click an IWebelement in a IList?

Viewed 3224

So I tried to click a button on YouTube, but I can't find the button by the Xpath because there are so many buttons, so I tried saving them in an IList, now I want to click a specific button in the list.

ChromeDriver chrome = new ChromeDriver();
List<IWebElement> textfields = new List<IWebElement>();
chrome.Navigate().GoToUrl("https://www.youtube.com/watch?v=9bZkp7q19f0");
textfields = chrome.FindElements(By.XPath("//*[@id=\"button"]")).ToList();
1 Answers

As per the documentation of Selenium FindElements(By.XPath("//*[@id=\"button"]")) will return a List of type ReadOnlyCollection<IWebElement>. So you can simplify your code like :

ChromeDriver chrome = new ChromeDriver();
List<IWebElement> textfields = new List<IWebElement>();
chrome.Navigate().GoToUrl("https://www.youtube.com/watch?v=9bZkp7q19f0");
textfields = chrome.FindElements(By.XPath("//*[@id='button']"));
foreach (IWebElement field in textfields)
{
    string my_text = field.GetAttribute("any_attribute_button_tag");
    Console.WriteLine(my_text);
}
Related