单击具有相同CssSelector或相同XPath FindElements的所有元素

时间:2014-07-15 07:46:25

标签: c# selenium xpath webdriver css-selectors

在Visual Studio中编写Selenium WebDriver的代码时,同一按钮的这两个代码只能运行一次。

点击按钮按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();

直到这一切都正确......


但我想点击所有按钮而不仅仅是第一个按钮,由于FindElements(复数形式)让我错误,如何点按所有按钮具有相同代码的按钮?

使用此获取错误:

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();

参见捕获:

enter image description here

3 个答案:

答案 0 :(得分:2)

您需要遍历FindElements结果并在每个项目上调用.Click()

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索引的尝试代码有效:

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

答案 1 :(得分:0)

List <WebElement> list = driver.FindElements(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']"));

然后迭代列表中包含的元素列表:

int x = 0;
while (x < list.size()) {
    WebElement element = list.get(x);
    element.click();
}

答案 2 :(得分:0)

你应该使用类似的东西(注意findElements中的s)

List<WebElement> textfields = driver.findElements(By.XPath("//button[@class='user-actions-follow-button js-follow-btn follow-button btn small small-follow-btn']"));

然后使用for循环进行迭代

for(WebElement elem : textfields){
    elem.click();
}