问题
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:
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);
}
来源:https://stackoverflow.com/questions/47485022/c-sharp-how-to-click-an-iwebelement-in-a-ilist