繁体   English   中英

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

[英]Click all elements with same CssSelector or same XPath FindElements

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

看到捕获:

在此输入图像描述

您需要遍历FindElements结果并在每个项目上调用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();
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();
}

你应该使用类似的东西(注意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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM