简体   繁体   中英

How to find the count of multiple buttons on a webpage using Selenium Webdriver

I have 4 Upload buttons on a webpage. Each of the upload button has the common functionality of uploading a file.

I am unable to get the count of these buttons using Selenium webdriver. The id of the buttons are:

  • buttonUpload_1
  • buttonUpload_2
  • buttonUpload_3
  • buttonUpload_4.

The common entity for these buttons is the class name buttonSecondary smallButton

I have tried the below commands to get the count, but was unable to:

List<WebElement> buttoncount = driver.findElements(By.className(("buttonSecondary smallButton")));

List<WebElement> buttoncount = driver.findElements(By.xpath("//input[@class='buttonSecondary smallButton']"));

You can get count using tagname as well

List<WebElement> buttons = driver.findElements(By.tagName("button"));
int buttonCount=0;
for(WebElement a : buttons){        
    if(a.getText().equals("buttonName")){
          buttonCount++;
}   
    System.out.println(buttonCount);
}

You can solve it with By.xpath locator, starts-with() function and getting the size() :

List<WebElement> buttons = driver.findElements(By.xpath("//button[starts-with(@id, 'buttonUpload_')]"));
System.out.println(buttons.size());

If your all button will have same class OR xpath like you have taken in question then you can get total button count like :

 System.out.Println(buttoncount.size());

Size() will return you total num. of buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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