Your ultimate guide

Showing posts with label Java with Selenium. Show all posts
Showing posts with label Java with Selenium. Show all posts

Find Elements

findElements() Method:
    findElements method finds the list of web elements on the web page. It returns an empty list if no elements are found.

Syntax:
    List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));


Example:
class Example
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.chorme.driver", "./chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://testingcolleges.blogspot.com");
        
        List<WebElement> allLinks = driver.findElements(By.tagName("a"));
        //print all the links (output: visible text -> Link)
        for(WebElement testing:allLinks)
        {
            System.out.println(testing.getText() + " -> " + testing.getAttribute("href"));
        }
        driver.close();
}


Select Multiple options in the dropdown using selenium with java

Select Multiple Items in the dropdown:
    When the dropdown is developed by using the <select> tag, then we can use the select class methods to automate single or multi-select dropdowns.
    In selenium, there is no specific method to Select multiple items in the dropdown. By using keyboard actions we can select multiple options in dropdown.

Example:
class Example
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver" , "./chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://");
        
        WebElement mDropdown = driver.findElement(By.name("1234")); 
        Select s = new Select(mDropdown);

        Actions a = new Actions(driver);
        a.keyDown(Keys.CONTROL)
            .click(s.getOptions().get(2))
            .click(s.getOptions().get(3))
            .click(s.getOptions().get(4))
            .keyUp(Keys.CONTROL)
            .build().perform();
    }
}

isMultiple():
    We can use this method to ensure whether the specified dropdown is a multi-select dropdown or not. This method returns True when the corresponding dropdown is multi-select.

Example:
WebElement ele = driver.findElement(By.id("tcg"));
Select s = new Select(ele);

if(s.isMultiple())  {
    System.out.println("The Dropdown is Multi-Select");
}
else  {
    System.out.println("The Dropdown is not Multi-Select")
}

- Next Page: FindElements

Handling Keyboard Actions using Selenium with Java

Keyboard Actions:
    When we want to use Mouse or Keyboard actions we should create an 'Actions' class object.

    Syntax: Actions object = new Actions(browser_object);
    Example: Actions act = new Actions(driver);

Method for Action Class:
    perform(): This method is used to execute the action.

The Keyboard interface has the below-mentioned methods:
sendKeys(KeyToSend): Sends a series of keystrokes onto the element.
Example: actions.sendKeys(Keys.DOWN).perform();
Keys.(DOWN, LEFT, RIGHT, UP, ENTER, DELETE, END, ESCAPE, F1-F12, NUMPAD0-NUMPAD9, INSERT, PAGE_DOWN, PAGE_UP, SEMICOLON, SPACE, SUBTRACT, MULTIPLY, ADD, DIVIDE, EQUALS, TAB, SHIFT)
- keyDown(theKey): Sends a key press Without releasing it.
        Example: action.keyDown(Keys.SHIFT).perform();
- keyUp(theKey): Performs a key release.
        Example: action.keyUp(Keys.SHIFT).perform();



Example program:
            class KeyboardAct
            {
                public static void main(String args[])
                {
                    System.setProperty("webdriver.gekco.driver", "./geckodriver.exe");
                    WebDriver driver = new FirefoxDriver();
                    driver.get("https://www.google.com");

                    WebElement searchBox =  driver.findElement(By.name("q"));
                    
                    Actions action = new Actions(driver);
                    action.moveToElement(searchBox)
                                .keyDown(searchBox, Keys.SHIFT)
                                .sendKeys(searchBox, "pokemon")
                                .keyUp(searchBox, Keys.SHIFT)
                                .pause(3000)
                                .sendKeys(Keys.DOWN)
                                .pause(3000)
                                .sendKeys(Keys.ENTER)
                                .perform();
                }
            } 

- Next Page: Select Multiple items in the dropdown

Handling Mouse Actions/Mouse Over using Selenium with Java

 Mouse Over:

    When we want to use Mouse or Keyboard actions we should create an "Actions" class object.

        Syntax: Actions object = new Actions(browser_object);
        Example: Actions act = new Actions(driver);

Method for Actions Class:

    build():- Build method in the Actions class is used to create a chain of actions or operations you want to perform.

    perform():- Perform Method in Action class is used to Execute a chain of actions that are built using the Action build method.




moveToElement(): This method is used to Move the Mouse point to a Particular Web Element.
Syntax: 
    Actions action_obj = new Actions(driver);
    WebElement ele = driver.findElement(By.id("123"));
    actions_obj.moveToElement("ele");

Example: 
class MousePnt
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver" , "./chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        
        // Create object instance for actions class
        Actions act = new Actions(driver);

        WebElement searchBox = driver.findElement(By.name("q"));
        act.moveElement(searchBox).perform();
        //act.moveElement(searchBox).click().perform();
    }
}


doubleClick(): This method is used to double-click on a particular web element.
    Syntax: actions_obj.doubleClick(WebElement).perform();

Example:
class DoubleClick
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver" , "./chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demoqa.com/buttons");
        Actions actn = new Actions(driver);
        
        WebDriver doubleClkBtn = driver.findElement(By.id("doubleClickBtn"));
        actn.doubleClick(doubleClkBtn).perform();
    }
}



contextClick(): To perform a (Mouse)Right-Click operation on a particular Web Element.
    Syntax: action_obj.contextClick(WebElement).perform();

Example:
class RightClick
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver" , "./chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://testingcolleges.blogspot.com");
        Actions actn = new Actions(driver);

        WebElement rClick = driver.findElement(By.name("q"));
        actn.contextClick(rClick).perform();
        //(or) actn.moveToElement(rClick).contextClick().perform();
    }
}
       
        


Handling mouse key hold & release:
    We can use the following methods to perform hold & release Keyword keys and Mouse keys.
    Syntax: action.clickAndHold(elementName).perform();
                 action.release(elementName).perform();


Handling Drag & Drop: 
    Some Web applications have the functionality to drag web elements and drop them on a defined area or element. We can automate the drag and drop of such elements using the Selenium web driver.

Syntax: action.dragAndDrop(SourceLocator, DestinationLocator);

Example:
class HandlingDragAndDrop
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        String url = "https://example.com";
        driver.get(url)
        
        WebElement dragMe = driver.findElement(By.id("123"));
        WebElement dropMe = driver.findElement(By.id("456"));

        Actions action = new Actions(driver);
        action.dragAndDrop(dragMe, dropMe).perform();
    }
}

- Next Page: Keyboard_Interactions

Handling Drop Down using Selenium with Java

 

Handling Drop Down:
    isDisplayed(): Determine if an element is displayed or not.
    isEnabled(): Determine if an element is enabled or not.
    
    selectByVisibleText(): This method selects the dropdown based on visible text
    selectByValue(): This method selects the dropdown based on the value attribute.
    selectByIndex(): This method selects the dropdown based on the index number.


.Example:



// First we need to get the main dropdown WebElement (select tag)
WebElement sdropdown = driver.findElement(By.id("tcg"));

// Then create an Object instance for Select Class(Pre-defined Class)
Select dpdown = new Select(sdropdown);

//To select an option by using Visible Text 
dpdown.selectByVisibleText(India);

//dpdown.selectByValue(ind); 
//dpdown.selectByIndex(4);





isMultiple():
    We can use this method to ensure whether the specified dropdown is a multi-select dropdown or not. This method returns True when the corresponding dropdown is multi-select. 
    That means In some dropdowns, we can able to select two or more elements at a time. In that situation by using 'isMultiple()' method we can find whether it was a multi-select dropdown or not.

Example Program:

WebElement ele = driver.findElement(By.id("tcg"));
Select s = new Select(ele);

if(s.isMultiple())
{
    System.out.println("The Dropdown is Multi-Select");
}
else
{
    System.out.println("The Dropdown is not Multi-Select");
}

getOptions():
    We can use this method to get all options in the specified dropdown.

Example Program:(To print all options in the dropdown)

{
    WebElement ele = driver.findElement(By.id("tcg"));
    Select s = new Select(ele);

    List<WebElement> l = s.getOptions();
    int size = l.size();
    for(int i=0; i<size; i++)
    {
        String options = l.get(i).getText();
        System.out.println(options);
    }
}

- Next Page: MouseOver and Drag-Drop

Handling Alerts with Selenium


Handling Alerts:
    In Selenium, alerts are popup dialog boxes that appear on a web page to provide information, take user input or request confirmation of specific actions. Selenium provides methods to interact with these alerts, allowing you to automate actions such as accepting, dismissing, or entering text into them.
Here's how you can work with alerts in Selenium:

switchTo().alert():
    To interact with an alert, you first need to switch the WebDirver's focus to it using the 'switchTo().alert()' method, and then we need to perform the action.
  1. Accept an Alert: Click OK an alert and close it
    • driver.switchTo().alert().accept();
  2. Dismiss an Alert: Click Cancel or the equivalent of an alert and close it.
    • driver.switchTo().alert().dismiss();
  3. Enter Text into a Prompt Alert: If the alert is prompt that requires you to enter text, you can use the 'sendKeys()' method to provide input.
    • driver.switchTo().alert().sendKeys("Your Input text");
  4. Get Text from an Alert: To retrieve the text displayed in an alert.
    • driver.switchTo().alert().getText();

Example Program:
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;

  5. public class Alert2 {
  6.   public static void main(String[] args) throws InterruptedException {
  7.     WebDriver driver = new ChromeDriver();
  8.     driver.get("https://testingcolleges.blogspot.com/2023/08/alerts-demo-pages.html");
  9.     WebElement confirmbox = driver.findElement(By.id("confirmbox"));
  10.     confirmbox.click();
  11.     driver.switchTo().alert().accept();
  12.     confirmbox.click();
  13.     driver.switchTo().alert().dismiss();
  14.     WebElement promptbox = driver.findElement(By.id("promptbox"));
  15.     promptbox.click();
  16.     driver.switchTo().alert().sendKeys("Happy");
  17.     driver.switchTo().alert().accept();
  18.   }
  19. }



 
switchTo().activeElement()
    To automate active element current webpage.
For example, when we open some websites, by default one element will be selected to select such type of active element we will use this method.

Example: driver.switchTo().activeElement().sendKeys(“Hello”);





Browser Windows Handling Using Selenium with Java


Window Handling:
    Window handling in Selenium refers to the process of interacting with multiple browser windows or tabs when automating web applications. Selenium provides methods and techniques to switch between different browser windows or tabs and perform actions on elements within each window.

Here are the Selenium methods to handle windows/tabs:
  1. switchTo().window()
  2. getWindowHandle()
  3. getWindowHandles()




switchTo():
    In Selenium, 'switchTo' is a method provided by the WebDirver API that allows you to switch the focus of WebDirver to different contexts within a web page. It is primarily used for switching between different frames, alerts, windows, or browser tabs when automating web applications.



switchTo().window():
    We can use this method to switch different browser windows or tabs by using its index number or window address.

Syntax(index): driver.switchTo().window("index");
Syntax(window address): driver.switchTo().window(address




getWindowHandle( ): 
    Each browser window has a specific address and it changes dynamically when the browser is opened, The WindowHandle() method gets the address of the active browser window and it has the return type as String.

Syntax: String currentWindow = driver.getWindowHandle();



getWindowHandles( ): 
    getWindowHandles gets the address of all the browser windows and it has the return of Set.

Syntax: Set<String> allWindows = driver.getWindowHandles();



  • Example Program:
  1. package Selinium_demo;
  2. import java.util.ArrayList;
  3. import org.openqa.selenium.By;
  4. import org.openqa.selenium.WebDriver;
  5. import org.openqa.selenium.chrome.ChromeDriver;

  6. public class WindowHandler2 {
  7.    public static void main(String[] args) {
  8.       WebDriver driver = new ChromeDriver();
  9.       driver.get("https://testingcolleges.blogspot.com/p/windowhandlingdemo1.html");
  10.       driver.findElement(By.xpath("//*[@id='post-body-8403560454683602685']/button")).click();

  11.       //getting all windows data into one ArrayList variable(win)
  12.       ArrayList<String> win = new ArrayList<String> (driver.getWindowHandles());
  13.       //Switching to 3rd window(index=2)
  14.       driver.switchTo().window(win.get(2));
  15.    }
  16. }




To print the Address of the browser windows:

// To print the unique ID of the current window

System.out.println(driver.getWindowHandle());

// To print the unique ID of all windows

System.out.println(driver.getWindowHandles());



To close all browser windows one by one:

ArrayList<String> win = new ArrayList<String> (driver.getWindowHandles());

// To Close all windows except 1st window(Index=0)

for(int i=1;i<=win.size();i++){

driver.switchTo().window(win.get(i));

driver.close();

}

- Next Page: Handling Alerts

Handling iframe/frame using Java with Selenium

Frames:
    In Selenium, 'frames' refer to HTML '<iframe>' elements on a web page. Frames are divide your browser window into multiple sections, and they are often used for things like displaying advertisements or loading content from external source.
    Example HTML source code for frames in a web page:
<iframe src="https://example.com" name="framename" id="framename" title="frametitle">
----
</iframe>

 

You may need to interact with elements inside frames. Here's how you can work with frames in Selenium:
  1. switchTo().frame()
  2. switchTo().defaultContent()
  3. switchTo().parentFrame()




1.  switchTo().frame():
    When a web element is located in an iframe tag in that situation first we need to switch into that frame then only we can access that web element.
    To change the web driver object from page level to frame level we will use switchTo().frame() method.

We can access the frame by using either the frame name, index or web element.
  1. By name:
    • If a frame has a 'name' or 'id' attribute, you can switch to it by specifying those attribute values.
    • Syntax: driver.switchTo().frame(frameName);
    • Example: Source Code: <iframe src="https://example.com" id="packageListFrame" name="frame1">
      • 1) driver.switchTo().frame(“packageListFrame”);
      • 2) driver.switchTo().frame(“frame1”)
  2. By Index:
    • Switching by index refers to the act of switching focus to specific frame using its index within the list of frames on a web page. Frames in HTML are numbered starting from 0. The index represents the position of the frame within the frameset or iframe tags. 
    • Syntax: driver.switchTo().frame(index number);
    • Example: driver.switchTo().frame(0);
  3. By Web Element:
    • If you have a reference to a WebElement representing the frame, you can switch to it.
    • Syntax: driver.switchTo().frame(WebElement);
    • Example:
      1. WebElement frame_element = driver.findElement(By.id(“q”));
      2. driver.switchTo().frame(frame_element);
 


 
2.  switchTo().defaultContent():
    We can use this method to change the web driver object frame level to the page level which means switching back to the main content from a frame.

    Example/Syntax: driver.switchTo().defaultContent();
 


3.  switchTo().parentFrame():
    This method is used to change focus from the current frame to the parent frame (Exit from the current frame and enter the previous frame).

    Example/Syntax: driver.switchTo().parentFrame();




Example Program:
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;

  5. public class FramesExample {
  6.   public static void main(String[] args) {
  7.     WebDriver driver = new ChromeDriver();
  8.     driver.get("https://testingcolleges.blogspot.com/p/testingframes.html");
  9.     
  10.     driver.switchTo().frame("demopckg");
  11.     WebElement userName = driver.findElement(By.id("001"));
  12.     userName.sendKeys("Testing");
  13.     
  14.     driver.switchTo().frame("bookmark");
  15.     WebElement password = driver.findElement(By.id("002"));
  16.     password.sendKeys("Colleges");
  17.     
  18.     driver.switchTo().parentFrame();
  19.     userName.clear();
  20.     
  21.     driver.switchTo().defaultContent();
  22.     WebElement refreshPage = driver.findElement(By.id("gjkl"));
  23.     refreshPage.click();
  24.     driver.close();
  25.   }
  26. }



Navigation Commands



Navigation Commands:
    Navigation Commands are used to navigate window base actions in the browser.


There are four types of Navigation Commands:

1.  navigate().to()
    Loads a new web page in the current browser window (replace the current URL with a new URL).
          Syntax: object.navigate().to(“URL”);
          Example: driver.navigate().to(“https://testingcolleges.blogspot.com/”);




2.  navigate().forward()
    It does the same operation as clicking on the forward button (→) of any browser.
          Example: driver.navigate().forward();



3.  navigate().back()
    It does the same operation as clicking on the back button (←) of any browser.
          Example: driver.navigate().back();



4. navigate().refresh()
    To refresh the current web page.
          Example: driver.navigate().refresh();