簡體   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