单击具有相同CssSelector或相同XPath FindElements的所有元素
在Visual Studio中编写Selenium WebDriver的代码时,同一按钮的这两个代码只能正常工作一次.
In Visual Studio writing the code for Selenium WebDriver, these two codes for the same button work fine only once.
点击按钮通过CSS选择器:
driver.FindElement(By.CssSelector(".follow-text")).Click();
点击按钮通过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...
但是我不想单击所有按钮,而不仅仅是单击第一个按钮,并且由于FindElements
(以复数形式)使我出错,我该如何按一下来单击所有按钮相同的代码?
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?
使用此获取错误:
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();
查看截图:
您需要遍历FindElements
结果并在每个项目上调用.Click()
:
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();
}
仅供参考,您需要将XPath括在方括号中,以使使用XPath索引的代码可以正常工作:
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();