Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click all elements with same CssSelector or same XPath FindElements

In Visual Studio writing the code for Selenium WebDriver, these two codes for the same button work fine only once.

Click the button By Css Selector:

driver.FindElement(By.CssSelector(".follow-text")).Click();

Click the button By XPath:

driver.FindElement(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")).Click();

Until this all correct...


But I want to click to all the buttons not to only the first, and because of the FindElements (in plural) get me error, how can I press click to all the buttons with that same code?

Using this get error:

List<IWebElement> textfields = new List<IWebElement>(); 
driver.FindElement(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']")).Click();
driver.FindElement(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn'][3]")).Click();

See the capture:

enter image description here

like image 479
Lion6 Avatar asked Feb 20 '26 23:02

Lion6


1 Answers

You need to loop through FindElements result and call .Click() on each item :

var result = driver.FindElements(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']"));
foreach (IWebElement element in result)
{
    element.Click();
}

FYI, you need to wrap the XPath in brackets to make your attempted code using XPath index works :

driver.FindElement(By.XPath("(//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn'])[3]")).Click();
like image 102
har07 Avatar answered Feb 22 '26 15:02

har07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!