单击具有相同CssSelector或相同XPath FindElements的所有元素 [英] Click all elements with same CssSelector or same XPath FindElements

查看:73
本文介绍了单击具有相同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();

这篇关于单击具有相同CssSelector或相同XPath FindElements的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆