top of page
Writer's pictureSudha Madhuri Basa

Selenium Methods Reference Guide

Selenium methods are predefined functions that allows us to interact with web elements and controls the behavior of the browser as per our requirement. These methods are categorized based on their purpose as stated below.


Browser Management Methods

Navigation Methods

Web Element Methods

Wait Methods 

Switch Methods


Methods in Selenium

1. Browser Management Methods - These methods allows you to control and interact with the browser window during automation. These methods are used for managing browser sessions, navigation, handling window etc.

 

  • get() - Navigates to the specified URL.  This method accepts URL in string format only.


Syntax :   driver.get(URL);


Example: WebDriver driver=new ChromeDriver();

 

 

  • getTitle() – This method retrieves the title of the current web page.


Syntax :   driver.getTitle();


Example: WebDriver driver = new ChromeDriver();

String title=driver.getTitle();

System.out.println("Page Title : "+title);

 

Output:  Page Title : About | Numpy Ninja

 

  • getCurrentUrl() – This method retrieves the URL of the current web page.


Syntax:  driver.getCurrentUrl();


Example: WebDriver driver = new ChromeDriver();

String currentURL=driver.getCurrentUrl();

System.out.println("Current URL : "+currentURL);

 

Output:   Current URL : https://www.numpyninja.com/

 

  • getPagesource() – This method returns us the complete source code of the current page.


Syntax:  driver.getPageSource();


Example: WebDriver driver = new ChromeDriver();

String pageSource = driver.getPageSource();

System.out.println("Current URL : " + pageSource);


Output:             HTML Code

   

  • getWindowHandle() - This method returns us the ID of the current browser window, it is unique and returns in string format.


Syntax:  driver.getWindowHandle();


Example: WebDriver driver = new ChromeDriver();

String windowHandle=driver.getWindowHandle();

System.out.println("Current Window Handle : "+windowHandle);

 

Output:   Current Window Handle : F9B21E104A0231942E4030BDC028B9F3

  

  • getWindowHandles() -  This method returns us the ID’s of the multiple browser windows,


Syntax: driver.getWindowHandles();


Example: WebDriver driver = new ChromeDriver();

driver.get("https://about.google/");

driver.findElement(By.linkText("Google Cloud")).click();

Set<String> windowIDs=driver.getWindowHandles();

System.out.println("Multiple Window Handles" +windowIDs);

 

Output:         Multiple Window Handles[736F1373DF4057CA39DB03A8ED91E9FD,

DF791A1C67A1EDB67095B021255AF8DA]


  • Maximize()  -   This method maximizes the browser window.

 

Syntax:  driver.manage().window().maximize();

 

  • Minimize()  - This method minimizes the browser window.

 

Syntax:   driver.manage().window().minimize();



2.  Navigation Methods  -  Selenium has provided us with various navigation methods which allows us to navigate between web pages such as moving forward and back and refreshing a page.

  

  • navigate().to(URL)   -  This method navigates us to specified URL.  This is equivalent to driver.get() method.

 

Syntax:   driver.navigate().to("URL");

 

Example:  WebDriver driver=new ChromeDriver();

                        driver.navigate().to("https://www.numpyninja.com/");                     

 

  • navigate().back()   -  This method navigates us to the previous page in the browser history.

 

Syntax:       driver.navigate().back();

 

Example:    WebDriver driver=new ChromeDriver();

driver.navigate().to("https://www.numpyninja.com/");    // page 1 

                   driver.navigate().to("https://dsportalapp.herokuapp.com/home// page 2 

                   driver.navigate().back(); // navigates to page 1

 

  • navigate().forward() – This method navigates us to one page forward in the browser history.

 

Syntax:       driver.navigate().forward();

 

Example:    WebDriver driver=new ChromeDriver();

driver.navigate().to("https://www.numpyninja.com/");    // page 1 

                     driver.navigate().to("https://dsportalapp.herokuapp.com/home");   // page 2          

                     driver.navigate().back();     // navigates back to page 1

                      driver.navigate().forward();   // navigates forward to page 2


  • navigate().refresh() – This method refreshes the current page.


Syntax:      driver.refresh();

 

Example:    WebDriver driver=new ChromeDriver();

                      driver.navigate().to("https://www.numpyninja.com/");

                      driver.navigate().refresh(); // refreshes the current page

 

 

3.  Web Element Methods : WebElement methods are used to interact with web elements on a web page during the test automation.  These methods allows us to perform actions like clicking buttons, entering data in to the text fields, retrieving data from the attributes etc.

 

  • findElement() -  The findElement() method is an important method that can help to get handle on web element.  It is the method which helps us to find the web element on the page before performing any action on it. If there are more than one element with the same locator then findElement() method is going to choose the first element.  That is why it is always better to use ID locator if it is available as ID is unique most of the time. Once the element located, we can perform actions like clicking and enter text into the input fields.

 

Syntax:  driver.findElement(locator);

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://www.numpyninja.com");

      WebElement text=driver.findElement(By.id("id_username"));

      text.sendKeys("Numpy");

 

 

  • sendKeys() –  This method sends the input to the input fields, text area or any other element which accepts user input.

 

Syntax:  element.sendKeys(“ Input Text”);

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

      WebElement text=driver.findElement(By.id("id_username"));

      text.sendKeys("Numpy");

 

 

  • click() – The click() method is used to perform a click action on a web element, such as button, link or any other clickable element on a web page.

 

Syntax:  element.click();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

      driver.findElement(By.linkText("Register")).click();

 

  • getText() -  getText() method is used to retrieve the text of a web element on a web page.  It helps fetch the heading, buttons, links or any element which contains visible text.

 

Syntax:              element.getText();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

String text=driver.findElement(By.linkText("Register")).getText();

      System.out.println("The link text is : "+text);

 

  • getAttribute() – This method retrieves the value of a specified attribute of the element.

 

Syntax: element.getAttribute(“attributeName”);

 

Example:  WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

     WebElement attriName= driver.findElement(By.name("username"));

      System.out.println("ID : "+attriName.getAttribute("id"));

 

  • getTagName() – This method retrieves the tag name of the element.

 

Syntax: element.getTagName();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

      WebElement name= driver.findElement(By.name("username"));

      System.out.println("Tag Name is :"+name.getTagName());

 

  • isDisplayed() -  This method checks if the web element is displayed or not.  It helps us to check whether the button, logo, checkbox, radio button, link is displayed or not.  It returns a boolean value, it returns true if the element is displayed and false if the element is not displayed.

 

Syntax: element.isDisplayed();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

boolean element=driver.findElement(By.linkText("NumpyNinja")).isDisplayed();

      System.out.println(“The logo is present”+element);

 

  • isEnabled() -  This method checks if the web element is currently enabled or not.  It helps us to understand whether the element can be interacted with or not, so that we can perform actions like clicking or typing. It returns a boolean value.

 

Syntax: element.isEnabled();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

      boolean element=driver.findElement(By.linkText("Register")).isEnabled();

      System.out.println(element);

 

  • isSelected() -  This method is used to check whether the web element, such as checkbox or radio button is selected or not.  It returns a boolean value.

 

Syntax: element.isSelected();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://login.yahoo.com/");

      boolean checkbox=driver.findElement(By.xpath("//input[@type='checkbox']")).isSelected();

      System.out.println("The checkbox is selected"+checkbox);

  

  • submit()  - This method is handy when interacting with forms on a web page. When we use this method it acts as an enter key.

 

Syntax: element.submit();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

      WebElement name= driver.findElement(By.xpath("//input[@type='submit']"));

      name.submit();


  • clear() – This method helps us to clear the text from an input or text area field. It is used to clear the existing text from the field before entering new text on it.

 

Syntax: element.clear();

 

Example: WebDriver driver = new ChromeDriver();

      driver.get("https://dsportalapp.herokuapp.com/login");

      WebElement name=driver.findElement(By.id("id_username"));

      name.sendKeys("Rockstars");

      name.clear();

          

4. Wait Methods – Wait methods are used to pause the execution until certain amount of time. Wait methods are used to solve the problem of synchronization in automation. Selenium provides us with different types of waits to handle synchronization issues between test execution and web page loading.


  • ImplicitWait() Method – Implicit Wait is a global wait and it applies to all elements on the page.  When we declare implicit wait, it’s the maximum amount of time that the driver waits for the elements to load before it throws NoSuchElementException.  If the element loads before time specified, execution continues without waiting.


Syntax:  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(seconds));


Example: WebDriver driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

 

  • ExplicitWait() Methods -  Explicit wait is used when the individual element takes more time to load.  Explicit waits are applied only to specific elements or conditions.  We can set maximum wait time for that particular element to load.  Some of the conditions in explicit wait are listed below:


o   elementToBeClickable()

o   elementToBeSelected()

o   textToBePresentInElement()

o   visibilityOf()

o   visibilityOfAllElements()

o   visibilityOfAllElementsLocatedBy()

o   visibilityOfElementLocated()


Syntax: WebDriverWait wait=new WebDriverWait(driver, Duration.ofSeconds(seconds));

              wait.until(ExpectedConditions.visibilityOfElementLocated(Locator));

 

Example: WebDriver driver = new ChromeDriver();

 

WebDriverWait wait=new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement name=wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id_username")));

name.sendKeys("Rockstars");

 

  • FluentWait() -    Fluent wait allows the driver to wait for a certain condition until the element is visible. It allows more flexibility over the waiting mechanism. Fluent wait applies locally to a specific element with conditions and polling frequency, it looks for a web element repeatedly at regular intervals until timeout or until the object is found.  We have an option to configure the wait to ignore any exception during polling period.

 

Syntax: Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

       .withTimeout(Duration.ofSeconds(seconds))

       .pollingEvery(Duration.ofSeconds(seconds))

       .ignoring(NoSuchElementException.class);

 

Example: WebDriver driver = new ChromeDriver();

          

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

                        .withTimeout(Duration.ofSeconds(10))

                        .pollingEvery(Duration.ofSeconds(2))

                        .ignoring(NoSuchElementException.class);

 

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id_username")));

 

element.sendKeys("Rockstars");


5. Switch methods  - Switch methods are set of functionalities within the switchTo() method which allows us to change the focus of driver to different elements on a webpage, such as switching between different windows, frames or alerts .

 

  • Switching between windows or tabs – To switch between the browser windows or tabs to interact with their elements.   Every browser window is identified by unique Window Handle.  

 

Syntax:  driver.switchTo().window(windowHandle);

 

Example: WebDriver driver=new ChromeDriver();

          

           driver.get("https://about.google/");

           String mainWindow=driver.getWindowHandle();

          

           driver.findElement(By.linkText("Google Cloud")).click();

          

           Set<String> windowIDs=driver.getWindowHandles();

           System.out.println("Multiple Window Handles" +windowIDs);

          

           for(String handle:windowIDs) {

                 if(handle.equals(mainWindow)) {

                      driver.switchTo().window(handle);

                      break;

                 }

           }

             

 

  • Switching  to frames or iframes – switch to a frame or a iframe to perform actions on that particular frame. It can switch to frame by its index or by its name/id or by using WebElement which represents the frame.

 

Syntax: driver.switchTo().frame(index);

driver.switchTo().frame(name or id);

driver.switchTo().frame(WebElement);

 

Example: WebDriver driver=new ChromeDriver();                    

driver.manage().window().maximize();

                            

//Frame1

WebElement frame1=driver.findElement(By.xpath("//frame[@src='frame_1.html']"));

driver.switchTo().frame(frame1); 

 

driver.findElement(By.xpath("//input[@name='mytext1']")).sendKeys("Welcome");

                            

driver.switchTo().defaultContent();  // switches back to the main content

                            

//Frame2

WebElement frame2=driver.findElement(By.xpath("//frame[@src='frame_2.html']"));

driver.switchTo().frame(frame2);

 

driver.findElement(By.xpath("//input[@name='mytext2']")).sendKeys("Automation");

                            

driver.switchTo().defaultContent();  // switches back to the main content

 


  • Switch back to the default content –  This method switches back to the main page

 

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

 

Example: WebDriver driver=new ChromeDriver();

                                                         

driver.manage().window().maximize();

                            

//Frame1

WebElement frame1=driver.findElement(By.xpath("//frame[@src='frame_1.html']"));

driver.switchTo().frame(frame1); 

 

driver.findElement(By.xpath("//input[@name='mytext1']")).sendKeys("Welcome");

                            

driver.switchTo().defaultContent();

 

 

  •  Switching to alerts –  Alerts are browser pop-ups which needs user interaction by clicking OK or Cancel.  Selenium allows switching to alerts for handling pop-ups.

 

Syntax: Alert alert= driver.switchTo().alert();

              alert.accept();  //Accepts the alert by clicking OK

              alert.dismiss(); //Dismisses the alert by clicking Cancel

              String alertTest=alert.getText();

              alert.sendKeys(“input”); // it sends input to a prompt alert

 

Example: WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

 

// 1) Normal alert with OK and Cancel button

driver.findElement(By.xpath("//button[normalize-space()='Click for JS Alert']")).click();

// opens alert box

 

Alert alert = driver.switchTo().alert();

alert.accept();

// or

alert.dismiss();

 

// or Prompt alert with input box

 

driver.findElement(By.xpath("//button[normalize-space()='Click for JS Prompt']")).click();

// opens alert

 

System.out.println("Alert Text:" + alert.getText());

 

alert.sendKeys("Hello NumpyNinja");

alert.accept();




Happy Reading..!!


 

28 views

Recent Posts

See All
bottom of page