Wednesday, June 26, 2024

findElement and findElements Methods and Difference between findElement() and findElements() in Selenium-Java

 

Using findElement and findElements Methods:

WebElement  findElement(By by):

  • Identifies/finds a single element on the web page using By class locators (e.g., id, name, class, xpath, CSS selector, link text, partial link text, tag name).
  • Returns the first matched WebElement (single element) if element is found
  • If the element is not found, it throws a NoSuchElementException.

Return Type: WebElement

 

 

 

List<Webelement> findElements(By by):

  • Identifies multiple elements on the web page using By class locators.
  • Returns a list of WebElement objects.
  • If no elements are found, it returns an empty list (does not throw NoSuchElement exception).

Return Type: List<WebElement>

When to Use:

  • To find and get multiple elements on a web page.
  • To handle a list of elements and perform actions on them.

 

when :     when  we want to find multiple elements

                                              to get multiple elements

                                           to handle multiple elements

 

ex: find all textboxes, checkboxes, radio button, multiple links

 

 Write xpath ,  How many textboxes are there on the page?

<input type="text"

-->  //input[@type='text']  6 ele

 

 

HW: Write xpath, How many password fields are there on the page?

 

HW: Write xpath, How many checkboxes are there on the page?

<inpute type="checkbox"  name= "any thing"

 

 

HW :Write xpath , How many radio buttons are there on the page?

<input type ="radio"

 

 

Write xpath  , How many buttons are there on the page?

<input type='button'

<input type='submit' >

 

<button >  </button>

 

//input[@type='button']   2 ele

//input[@type='submit']    1 ele

//button   1 ele

 

//input[@type='button']|//input[@type='submit'] |  //button   4 ele 4 buttobs

 

 

Write xpath for buttons, type= buttton or type=submit?

//input[@type='button'] | //input[@type='submit']    3 ele

 

HW Write xpath for buttons, type= buttton or button?

 

HW Write xpath  , How many buttons are there in page where  type=button or submit or button.

Note: for above Question, use and or |   symbols in xpath?

 

 

 

HW : Write xpath , How many dropdowns are there on the page?

<select >

 

 

 

HW : Write xpath , How many links are there on the page?

<a href= ""  >   gmail </a>

 

 

HW : Write xpath  , How many images are there on the page?

<img  src = "" > 

 

Handling Multiple Textboxes:

 

ex: allTextboxes - program

package WebelementsBasics;

 

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class HandlingMultipleTextboxes {

 

            public static void main(String[] args) throws InterruptedException {

 

                        //open chrome browser                    

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver = new ChromeDriver();

 

                        Thread.sleep(3000);

                        // open url -file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html");

 

            //  get count of all textboxes in page -   findElement() -   findElements()

                        List<WebElement>  allTextboxesList = driver.findElements(By.xpath("//input[@type='text']"));

                        int allTextboxesCnt  = allTextboxesList.size();

 

                        System.out.println("allTextboxesCnt="+allTextboxesCnt);//

//                                                                                 allTextboxesCnt=6

                       

                        // get "first text box" - from allTextboxes and enter 'first ' in first textbox

                        allTextboxesList.get(0).sendKeys("first");

 

 

                        // enter 'second ' value in 2nd element from all textboxes

                        allTextboxesList.get(1).sendKeys("second");

 

 

                        //  HW  enter '3rd ' values in 3rd textbox from all textboxes

 

                        //HW  enter ' 4 th ' values in 4th textbox from all textboxes

 

 

                        //  enter 'Swathi' in all text boxes

                        // 1. using for loop with index  no    

//                     for(int i=0;i<=allTextboxesCnt-1 ; i++)

//                     {

//                                 if(allTextboxesList.get(i).isEnabled())

//                                 {  //  if ele is enabled - send data to textbox

//                                             //         false

//                                             allTextboxesList.get(i).clear();

//                                             allTextboxesList.get(i).sendKeys("Swathi");

//                                 }

//                                

//                     }

 

                        //                     Exception in thread "main" org.openqa.selenium.ElementNotInteractableException: element not interactable

 

                        //if ele (txt box) is disabled - if we try to clear data, enter data in text box- we will get ElementNotInteractableException

 

 

 

                        //******************************************************

                        //  2 nd use for each loop

                        //                     use for each loop for array list

 

                        for(WebElement  eachEle : allTextboxesList)

                        {

                                    if(eachEle.isEnabled())

                                    {

                                                eachEle.clear();

                                                Thread.sleep(2000);

                                                eachEle.sendKeys("Raju");

                                    }

                                   

                        }

                        //                                             Exception in thread "main" org.openqa.selenium.InvalidElementStateException:

                        //                                                         invalid element state: Element is not currently interactable and may not be manipulated

                        //if ele (txt box) is disabled - if we try to clear data, enter data in text box-

 

 

                        //                     Exception in thread "main" org.openqa.selenium.ElementNotInteractableException:

                        //                                 invalid element state: Element is not currently interactable and may not be manipulated

                        //if ele (txt box) is disabled - if we try to clear data, enter data in text box- we will get ElementNotInteractableException

 

                        //For example, trying to click on an element that is covered by another element or trying to interact with a disabled element may result in this exception.

 

 

 

                        //***************************************

                        // HW 3. way use iterartor ()                                     

 

                        // HW 4  way use listiterator()                                  

 

 

 

            }

 

}

 

 

**************************************************                   

 

**************************************************

Note:

----------

 

            //  get all div tags       

                                                List<WebElement> allTexboxesList =            driver.findElements(By.xpath("//div"));

                                               

                                                // if there is no element found using By class locator  , it does not throw NoSuchElementException

                                                //  it returns empty list

                                               

                                                 int txtboxesCnt=  allTexboxesList.size();// 0

 

Handling Multiple Checkboxes

When dealing with multiple checkboxes on a webpage, you can use Selenium to identify and interact with these elements using the findElements method.

 

ex: AllCheckboxesBasics

 

package WebelementsBasics;

 

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class AllCheckboxesBasics {

 

            public static void main(String[] args) throws InterruptedException {

                       

                        //open chrome browser                    

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver = new ChromeDriver();

 

                        Thread.sleep(3000);

                        // open url -file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html");

                       

                        // get all 'checkboxes' cnt      

                        List<WebElement> allCheckboxesList =   driver.findElements(By.xpath("//input[@type='checkbox']"));

                        int checkboxesCnt =   allCheckboxesList.size();

 

                        System.out.println("checkboxesCnt ="+checkboxesCnt);

 

                        //  Click first check box

//                     allCheckboxesList.get(0).click();

 

                        //  click 2nd checkbox

//                     allCheckboxesList.get(1).click();

                       

                        // HW clikc 3rd checkbox

 

                        //HW  click 4 th check box                

 

                        //   4  checkboxes 0 - 3

 

                        // click 5 th check box

//                     allCheckboxesList.get(5).click();

           

                        //                                             allcheckBoxesList.get(5).click();// error  :  dont have index no 5

                        //java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 4

 

 

                        //  1.Click all checkboxes using for loop with index no

                        for(int i=0;i<=allCheckboxesList.size()-1;i++)

                        {

                                    Thread.sleep(2000);

                                    allCheckboxesList.get(i).click();

                        }

                       

 

                        //  HW 2.Click all checkboxes using for each loop                            

 

                        // HW 3.Click all checkboxes using iterator ()           

 

                        // HW 4.Click all checkboxes using listIterator()                   

 

                        //  HW unselect all check boxes

                        // hint :   if checkbox is selected --  click

 

 

 

            }

 

}

 

Handling Multiple Links:

 

When dealing with multiple links on a webpage, you can use Selenium to identify and interact with these elements using the findElements method.

 

package WebelementsBasics;

 

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class AllLinks {

 

            public static void main(String[] args) throws InterruptedException {

                        //open chrome browser                    

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver = new ChromeDriver();

 

                        Thread.sleep(3000);

                        // open url -file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html");

 

                        ///   get all Links count :  input , a , select  --->   <a href =" url"> My Gmail  </a>

                        List<WebElement> allLinks = driver.findElements(By.xpath("//a"));

                        int linksCnt = allLinks.size();

                        //                    3

                        //  linksCnt =  3

                        System.out.println("linksCnt="+linksCnt);

                        //                                3

                       

                        // get 1st link and click

//                     allLinks.get(0).click();// clikc My gmail link

 

                        // get fist link text -- o/p:  My Gmail

                        String firstLinkText =  allLinks.get(0).getText();

                        //                        My Gmail

                        //  firstLinkText  = My Gmail

                        System.out.println("firstLinkText="+firstLinkText);// My gmail

 

                        // HW get 2nd link and its text  (Open Face book)

 

                        // HW get 3rd link and its text (Open Amazon Link)

 

 

                        // get 9th link text

//                     allLinks.get(9).getText();

                        //                                             System.out.println("ninthLinkText=");

                        // IndexOutOfBoundsException: Index 9 out of bounds for length 9

                        // bcoz we dont have index no = 9   as list stores values/ elements in index no  0 to 2 .

 

 

           

                        // get 1st Link  url (href)

                        String firstLinkUrl = allLinks.get(0).getAttribute("href");

                        // firstLinkUrl  = https://www.google.com/intl/en-GB/gmail/about/

                        System.out.println("firstLinkUrl="+firstLinkUrl);

                        //                                  https://www.google.com/intl/en-GB/gmail/about/

                       

                        //HW  get 2nd link url

 

                        // HW get 3rd link url

 

 

                        // get all visible link texts from page  using for loop with index no?

                        //  100 links

//                     .allLinks get(0)

                        //        gte(1)

                        //          ...

                        //   get (99);

                        for(int i=0;i<= allLinks.size()-1;i++)

                        {//     i=0         3-1=2

                                   

                                    String linkText = allLinks.get(i).getText();

                                    System.out.println("linkText="+linkText);

                        }

 

                        //                                                                     linkText=My gmail

                        //                                                                     linkText=Open Facebook

                        //                                                                     linkText=Open amazon

                        //                                                                    

                        //**************************************************

                        // HW   // get all visible link texts from page  using for each loop

 

 

 

                        // 3 .HW  // get all visible link texts from page  using iterator()

 

 

 

                        // 4 .HW   // get all visible link texts from page  using listiterator()

 

 

 

            }

 

}

 

 

 

HW  get all link urls using for loop, foreach loop , iterator(), listiterator()   ?

 

           

FAQ : WAP to  get all link names and  urls using tagname ?

 

            ///  get all Links count :   id(), name() .classname() ,  xpath ("//a"), CssSelector("a")   linktext()

                        // partilaLinktext() 

        tagName("a")  // a , input, select,  option, img

 

// we can use tag names also

 

code using tagname:

package WebelementsBasics;

 

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class AllLinks {

 

            public static void main(String[] args) throws InterruptedException {

                        //open chrome browser                    

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver = new ChromeDriver();

 

                        Thread.sleep(3000);

                        // open url -file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/SampleWebpage.html");

 

                        ///   get all Links count :  input , a , select  --->   <a href =" url"> My Gmail  </a>

//                     List<WebElement> allLinks = driver.findElements(By.xpath("//a"));

                        List<WebElement> allLinks = driver.findElements(By.tagName("a"));

                        int linksCnt = allLinks.size();

                        //                    3

                        //  linksCnt =  3

                        System.out.println("linksCnt="+linksCnt);

                        //                                3

                       

                        // get 1st link and click

//                     allLinks.get(0).click();// clikc My gmail link

 

                        // get fist link text -- o/p:  My Gmail

                        String firstLinkText =  allLinks.get(0).getText();

                        //                        My Gmail

                        //  firstLinkText  = My Gmail

                        System.out.println("firstLinkText="+firstLinkText);// My gmail

 

                        // HW get 2nd link and its text  (Open Face book)

 

                        // HW get 3rd link and its text (Open Amazon Link)

 

 

                        // get 9th link text

//                     allLinks.get(9).getText();

                        //                                             System.out.println("ninthLinkText=");

                        // IndexOutOfBoundsException: Index 9 out of bounds for length 9

                        // bcoz we dont have index no = 9   as list stores values/ elements in index no  0 to 2 .

 

 

           

                        // get 1st Link  url (href)

                        String firstLinkUrl = allLinks.get(0).getAttribute("href");

                        // firstLinkUrl  = https://www.google.com/intl/en-GB/gmail/about/

                        System.out.println("firstLinkUrl="+firstLinkUrl);

                        //                                  https://www.google.com/intl/en-GB/gmail/about/

                       

                        //HW  get 2nd link url

 

                        // HW get 3rd link url

 

 

                        // get all visible link texts from page  using for loop with index no?

                        //  100 links

//                     .allLinks get(0)

                        //        gte(1)

                        //          ...

                        //   get (99);

                        for(int i=0;i<= allLinks.size()-1;i++)

                        {//     i=0         3-1=2

                                   

                                    String linkText = allLinks.get(i).getText();

                                    System.out.println("linkText="+linkText);

                        }

 

                        //                                                                     linkText=My gmail

                        //                                                                     linkText=Open Facebook

                        //                                                                     linkText=Open amazon

                        //                                                                    

                        //**************************************************

                        // HW   // get all visible link texts from page  using for each loop

 

 

 

                        // 3 .HW  // get all visible link texts from page  using iterator()

 

 

 

                        // 4 .HW   // get all visible link texts from page  using listiterator()

 

 

 

            }

 

}

                       

FAQ *** Difference Between findElement() and findElements()?

 

Feature

findElement()

findElements()

Purpose

Locate a single web element

Locate multiple web elements

Return Type

WebElement

List<WebElement>

Number of Elements

Returns the first matching element

Returns a list of all matching elements

Behavior if Not Found

Throws NoSuchElementException

Returns an empty list

Exception Handling

Yes, if the element is not found

No exception is thrown if no elements are found

Use Case

Single element interaction

Multiple elements interaction

Example Usage

Filling a form field, clicking a button

Iterating through links, checking checkboxes

Syntax Example

driver.findElement(By.id("username"))

driver.findElements(By.tagName("a"))

 

// findElement()  used to identify or find element on web page using By Class locators i.e id, name , class, xpath, Csselector, Linktext, partialLinktext,tagname()

 

 

                        //  always returns the first matched element if multiple elements are found in page --  using By class locators

                        //  if ele is not found ,  it throws exception --> 'NoSuchElementException

                        // return type of findElemnt():  WebElement

//  if we want to handle single ele, we can go for findelement()

           

ex:      

                        WebElement  firstNameTextboxEle =             driver.findElement(By.name("fname"));

                        firstNameTextboxEle.sendKeys("raju");

                       

//                     driver.findElement(By.name("middlename")).sendKeys("middle");//  not ok

 

                        //   'NoSuchelement Exception' -- it goes to html page  seach for all tags where name= 'middlename'

                        //  but there are no elements found in page, it throws NoSuchElementException

                        // org.openqa.selenium.NoSuchElementException:

                        //no such element: Unable to locate element: {"method":"css selector","selector":"*[name='middlename']"}

                       

                       

                        // findElements(): can be used to handle multiple elements using By class locators

                        //   returns list of webelments  and stores into list

                        // if ele is not found in page, it returns empty list  but  it does not throw -NoSuchElementException

                        // return type of findElements()  - List<WebElement>

                       

                        List<WebElement>  allEle =  driver.findElements(By.xpath("//a[text()='amazon']"));

                        //                                  empty list    

            //  if we want to handle multiple elemnsts (text boxes, check boxes,,links etc) , we can go for findelements()

 

// HW WAP  to Get Count of All Dropdowns from the Page

// HW WAP  to Get Count of All Paragraphs from the Page

// HW WAP  to Get Count of All Input Tags from the Page

// HW WAP  Get Count of All Images from the Page

 

// HW WAP  to get count of all buttons and button names?

ex :    Login, Submit

//input[@type='button']  - 1 ele

//input[@type='submit']  2  ele

//button  - 1 el

 

hint :  use  | OR   symbol in xpath ?

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...