Monday, August 26, 2024

Webdriver and Methods

Webdriver(I):

Webdriver (I) -  is predefined interface in Selenium.

-   represents any type of browser

                  -- chrome browser

                             Edge

                            ff

                           IE 

- Predefined methods can be used to control browser common operations like

Common Operations:

·        Open URL: Load a web page URL in the browser.

·        Close Browser: Close the current browser window.

·        Quit: Close all browser windows and safely end the WebDriver session.

·        Locate Elements: Find and interact with elements on a web page.

·        Find Multiple Elements: Locate multiple elements matching a specified selector on a web page

     

Important Methods in WebDriver Interface:

The WebDriver interface in Selenium provides essential methods for automating interactions with web browsers. Here’s an overview of some key methods:

Refer API doc:

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebDriver.html

1. get(String url):

  • Purpose: Opens the specified URL in the current browser window.
  • Usage: driver.get("https://www.example.com");
  • Example: Loads the webpage located at "https://www.example.com".

2. getTitle():

  • Purpose: Retrieves the title of the current web page.
  • Usage: String title = driver.getTitle();
  • Example: Retrieves the title of the currently open browser tab.

3. getCurrentUrl():

  • Purpose: Retrieves the URL of the current web page.
  • Usage: String currentUrl = driver.getCurrentUrl();
  • Example: Returns the URL currently displayed in the browser.

4. getPageSource():

  • Purpose: Retrieves the HTML source code of the current web page.
  • Usage: String pageSource = driver.getPageSource();
  • Example: Fetches the entire HTML content of the currently open page.

5. navigate().to(String url):

  • Purpose: Navigates the browser to the specified URL.
  • Usage: driver.navigate().to("https://www.example.com");
  • Example: Similar to get(String url), but can be used for navigation chaining.

6. close():

  • Purpose: Closes the current browser window that is currently focused.
  • Usage: driver.close();
  • Example: Closes the active browser tab or window.

7. quit():

  • Purpose: Closes all browser windows and ends the WebDriver session.
  • Usage: driver.quit();
  • Example: Terminates all browser instances opened by Selenium WebDriver.

quit(): to close all browser windows which are opened by Selenium

            ex:  if Selenium code opens 3  or 4 browser windows, quit() -can be used close all browser windows

8. findElement(By by):  can be used to find the element in page using By class locators

                                        to identify the element in page

                                        to locate the element in page

  Usage: WebElement element = driver.findElement(By.id("elementId"));

  Example: Finds the HTML element identified by its id attribute.

9. findelements(By by):  to find the list of elements  in page using By class locators

                        locate

                     identify

  Usage: List<WebElement> elements = driver.findElements(By.className("className"));

  Example: Retrieves a list of HTML elements identified by their className attribute.

getWindowHandle()  --> Later

getWindowHandles() --> Later

code:

package SeleniumBasics1;

import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserBasicsMethods1 {

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

                       

                        //open chrome browser

//                     2 steps

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

                        ChromeDriver driver =  new ChromeDriver();

                       

                        // we can store Chromdriver class obj reference in webdriver interface var

                        //  driver  - refers chrome browser

                        //    Edgedriver

                        // firefoxdriver

                        // to open the url in chrome browser --> get("url")

                        //https://www.amazon.com/

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

                        //  chrome browser

                        //                     Thread.sleep(3000);

                        // get current url

                        String  currentURL = driver.getCurrentUrl();

                        //                       https://www.amazon.com/

                        //                

                        //    currentURL  = https://www.amazon.com/

                        System.out.println("url=" + currentURL);

                        //

                        // get title of page

                        String getTitle  = driver.getTitle();

                                    //                  Amazon.com

                        //               

                        // getTitle  =  Amazon

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

                        //                      Amazon.com

                        // get page source code of browser page

                        String htmlcode= driver.getPageSource();

                                                            //                     // htmlcode=<html class="a-no-js" lang="en-us"><!--<![endif]--><head>

                                                            ////                  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

                                                            ////                  <meta charset="utf-8">

                                                            ////                  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

                                                            //                     <title dir="ltr">Amazon.com</title>

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

                        Thread.sleep(3000);

                        // close()

                        // close the currently focussed browser window

//                     driver.close();

                        //  quit() to close all browser windows which are opened by Selenium

                        driver.quit();

                       

                        // FAQ Difference between  close and quit()

                        //FindElement()

                        // findElements()

                        // getWindowHandle()

                        //                                             getWindowHandles()

 

            }

}

get ()   and Navigate():

package SeleniumBasics1;

import org.openqa.selenium.chrome.ChromeDriver;

public class GetAndNavigateDifference  {

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

                        //2  create obj for ChromeDriver- Class

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

                        ChromeDriver driver = new ChromeDriver();

                       

                        // open some url in browser-https://www.amazon.com/

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

                        //  get()  it waits till it loads all elements in the page  , then only it goes to next stmt

                        Thread.sleep(5000);

                        // open https://www.facebook.com/

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

                        // navigate() -  it does not wait till it loads all elements in the page

                        //                                 Thread.sleep(5000);

                        // to navigate to previous page --https://www.amazon.com/

                        driver.navigate().back();

                        Thread.sleep(5000);

                        //  go to next page

                        driver.navigate().forward();

                        //used to navigate to  next page based on browser history

                        //https://www.facebook.com/

                        // Refresh page

                        Thread.sleep(5000);

                        driver.navigate().refresh();

                        // FAQ Difference  get() and Navigate()

            }

}

FindElement( By  by ):

can  find element / locate ele / identify the ele in web page  using By class locators

(by using id, name, class.. etc) and returns 1st matched web ele.

Usage:

  • WebElement element = driver.findElement(By.id("elementId"));

By class Locators :

-------------------

 is predefined class in Selenium

 has some methods to identify the element in web page

           

            Male <input type="radio" name = "male" id = "maleid"  class='firstclass'>

            Female<input type="radio" name= "female" id= "femaleid">

The By class in Selenium provides several methods that return instances of By representing different locator strategies to find elements on a web page:

  • By.id("idValue"): Locates an element by its id attribute.
  • By.name("nameValue"): Locates an element by its name attribute.
  • By.className("classNameValue"): Locates an element by its class attribute.
  • By.xpath("xpathExpression"): Locates an element using an XPath expression (advanced).
  • By.cssSelector("cssSelectorExpression"): Locates an element using a CSS selector (advanced).
  • By.linkText("linkText"): Locates an <a> element by its exact link text.
  • By.partialLinkText("partialLinkText"): Locates an <a> element by partial link text.
  • By.tagName("tagName"): Locates elements by their HTML tag name.

 By.id("id val");   --->  By.id("maleid")   -->  id =   'maleid'

 By.name("name val"); --> By.name("male")  --> name  =male

 By.classname("class value") --> By.className("firstclass") -->  class = firstclass

 

By.xpath("") -- >  By.xpath(" write xpath for desired element")  --> Later classes

By.cssSelector("") - >  By.CssSelector("Write CSS selector path")  -->Later classes

            <a href ="https://www.google.com" > Click My google  <a>

 

By.Linktext("Link text") - Click My google -- > By.linkText("Click My google ")   -->  give full link text

By.partialLinkText(" pass partial link text ") -> Click My google  -- >    -->

            By.partialLinkText("Click")

            By.partialLinkText("My google")

            By.partialLinkText("google")

             

By.tagName(" pass tag name ")  --> By.tagname("p")

                                                By.tagname("input")

                                                By.tagname("a")

                                                By.tagname("select")

 

FAQ Can you tell me locator names ?

HW    open chrome browser  and enter url Facebook.com, get title and get current url and navigate to redbus.com and get title and get current url , close the browser.

HW open chrome browser , enter url - Facebook.com and navigate to redbus.com and get title and get current url,

,  go to previous page, get title, get url ,

 go to next page and get title , get url ?

Refer API Docs:

Search 'downloads Selenium' > Click on offical website  > go to Java section > Click 'API Docs' > it opens API  doc page>  Search for any predefine class or interface i.e Webdirver or ChromeDriver-->  click respective value > it opens 'Webdriver' details    and all Methods.. 

Modifier and Type, Method , Description

https://www.selenium.dev/selenium/docs/api/java/index.html

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebDriver.html

Change log:

-------------------

Refer change log :

https://github.com/SeleniumHQ/selenium/blob/trunk/java/CHANGELOG

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...