Your ultimate guide

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

File Upload Using Selenium WebDriver

Exploring Different Approaches for File Upload with Selenium WebDriver:

........Incomplete.......
    File uploads are a common functionality on web applications, and automating this process is crucial for efficient testing with Selenium WebDriver. In this blog post, we will explore three different methods to upload files using Selenium WebDriver: 'SendKeys', the 'Robot' class, and 'AutoIT'.

Using SendKeys:
    The most straightforward approach for uploading a file in Selenium WebDriver is to use the 'SendKeys' method. This method is applicable only if the HTML input element has the attribute type="file". This attribute is specific to file upload functionality, and using Selenium's sendKeys method allows for the automatic selection of the desired file for this type of input field.
Syntax:
  1. WebElement fileInput = driver.findElement(By.id("idvlaue"));
  2. fileInput.sendKeys("path/to/your/file.txt");
Pros:
  • Directly interacts with the file input element.
  • Simple and concise code for file uploads.
  • No external dependencies are required.
Cons:
  • Limited to scenarios where the file input element is present.

Using Robot Class:
    The Robot class in Java can be used to simulate keyboard and mouse actions. In the context of the uploads, the Robot class can be used to navigate the file selection dialogue.

Example Program:
  1. import java.awt.AWTException;
  2. import java.awt.Robot;
  3. import java.awt.Toolkit;
  4. import java.awt.datatransfer.StringSelection;
  5. import java.awt.event.KeyEvent;
  6.  
  7. import org.openqa.selenium.By;
  8. import org.openqa.selenium.WebDriver;
  9. import org.openqa.selenium.WebElement;
  10. import org.openqa.selenium.chrome.ChromeDriver;
  11. import org.openqa.selenium.chrome.ChromeOptions;
  12.  
  13. public class Dummy2 {
  14. public static void main(String[] args) throws AWTException {
  15. ChromeOptions co = new ChromeOptions();
  16. co.addArguments("-remote-allow-origins");
  17.  
  18. WebDriver driver = new ChromeDriver();
  19.                 driver.get("https://testingcolleges.blogspot.com/2024/01/file-upload-demo-page.html");
  20.  
  21. WebElement fileUploadBtn = driver.findElement(By.className("file-label-2"));
  22. fileUploadBtn.click();
  23.  
  24. Robot rbt = new Robot();
  25. rbt.delay(2000); // just like thread.sleep
  26.  
  27. //these below 2 lines used to copy the path 
  28. StringSelection ss = new StringSelection("C:\\Users\\Dollar\\Desktop\\Dummy.txt");
  29. // copy the above path in clipboard
  30. Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
  31. //Toolkit.getDefaultToolkit().getSystemClipboard().setContents("path", null);
  32.  
  33. //perform Ctrl+V operation to pass the copied path
  34. rbt.keyPress(KeyEvent.VK_CONTROL);
  35. rbt.keyPress(KeyEvent.VK_V);
  36. rbt.keyRelease(KeyEvent.VK_CONTROL);
  37. rbt.keyRelease(KeyEvent.VK_V);
  38.  
  39. //Enter press
  40. rbt.keyPress(KeyEvent.VK_ENTER);
  41. rbt.keyRelease(KeyEvent.VK_ENTER);
  42.  
  43. }
  44. }

Pros:
  • Works across different browsers.
  • Can handle scenarios with hidden file input fields.
Cons:
  • Requires handling keyboard events, which may be error-prone.
  • Platform-dependent and may need adjustments for different operating systems.
Using AutoIT:
    AutoIT is a scripting language designed for automating the Windows GUI and general scripting tasks. It can be integrated with Selenium WebDriver to handle file Uploads.
Pros:
  • Powerful for handling complex file upload scenarios.
  • Works seamlessly across different browsers and operating systems.
Cons:
  • Requires installing AutoIT and writing an external script.
  • Add an external dependency to your automation project.


Conclusion:
    Each method for file upload with Selenium WebDriver has its advantages and limitations. The choice of method depends on the specific requirements of your application and the level of control and compatibility needed. While SendKeys is suitable for simple scenarios, the Robot class and AutoIT offer more flexibility and control, making them valuable tools for handling complex file upload functionalities.




Browser Window Sizes and Positions


maximize(): The maximize() method is used to maximize the browser window. This is often done to ensure that the web page is displayed in its full size on the screen. Here's an example of how you can use the 'maximize' method in selenium with Java:

  1. public class Maximize {
  2.     public static void main(String[] args) {
  3.         WebDriver driver = new ChromeDriver();
  4.         driver.manage().window().maximize();
  5.     }
  6. }

How to Minimize the Browser Window in Selenium?
    Selenium's Java has no built-in method to minimize the browser window. However, Selenium's Python does have a minimize function.




getSize(): The getSize() method is used to get the height and width of a WebElement/BrowserWindow. The getSize() method returns an object of type 'Dimension', and you can use its 'getHeight' and 'getWidth' methods to obtain the height and width, respectively.

Example 1: To get the height and width of a web element.
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.Dimension;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.WebElement;
  5. import org.openqa.selenium.chrome.ChromeDriver;
  6. public class GetElementSize {
  7.     public static void main(String[] args) {
  8.         WebDriver driver = new ChromeDriver();
  9.         driver.get("https://example.com");
  10.         WebElement element = driver.findElement(By.id("value"));
  11.         Dimension size = element.getSize();
  12.         System.out.println("Height: " + size.getHeight());
  13.         System.out.println("Width: " + size.getWidth());
  14.     }
  15. }
Example 2: To get the height and width of a Browser Window.
  1. import org.openqa.selenium.Dimension;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. public class GetBrowserWindowSize {
  5.     public static void main(String[] args) {
  6.         WebDriver driver = new ChromeDriver();
  7.         driver.get("https://example.com");
  8.         Dimension windowSize = driver.manage().window().getSize();
  9.         System.out.println("Window Height: " + windowSize.getHeight());
  10.         System.out.println("Window Width: " + windowSize.getWidth());
  11.     }
  12. }
Note: In the above example instead of creating the Dimension class object we can also directly give the methods:
driver.manage().window().getSize().getHeight();
driver.manage().window().getSize().getWidth();




Resize the Browser window:
    To resize the Browser window. 'manage().window().setSize()' is a predefined method of the Selenium 'WebDriver' class.
Syntax 1:
  1. Dimension newSize = new Dimension(800, 600); //(width, height)
  2. driver.manage().window().setSize(newSize);

Syntax 2:
  1. driver.manage().window.setSize(new Dimension(800, 600));

Example:
  1. import org.openqa.selenium.Dimension;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. public class ResizeWindow {
  5.     public static void main(String[] args) {
  6.         System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
  7.         WebDriver driver = new ChromeDriver();
  8.         driver.get("http://example.com/");
  9.         Dimension newSize = new Dimension(800, 600);
  10.         driver.manage().window().setSize(newSize);
  11.     }
  12. }
Note: In Eclipse, you may have recommend two import statements for the 'Dimension' class: 'import java.awt.Dimension;' and 'import org.openqa.selenium.Dimension;'. You should only select 'import org.openqa.selenium.Dimension;'. 




getPosition():
    getPosition() method gets the position of the current window, relative to the upper left corner of the screen. The method takes no arguments and returns a Point object, which contains the X and Y coordinates of the window.

Syntax:(With Point object)
  1. // Get the position of the current window
  2. Point p = driver.manage().window().getPosition();
  3. // Print the X and Y coordinates of the window
  4. System.out.println("X Coordinate: " + p.getX());
  5. System.out.println("Y Coordinate: " + p.getY());
Syntax: (We can also print the X and Y Coordinates without creating a Point object)
  1. System.out.println("X Coordinate: "driver.manage().window().getPosition().getX());
  2. System.out.println("Y Coordinate: " + driver.manage().window().getPosition().getY());

Example:
  1. import org.openqa.selenium.WebDriver;
  2. import org.openqa.selenium.chrome.ChromeDriver;
  3. public class WindowPosition {
  4.     public static void main(String[] args) {
  5.         System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
  6.         WebDriver driver = new ChromeDriver();
  7.         driver.get("http://testingcolleges.blogspot.com/");
  8.         System.out.println("X Coordinate: " + driver.manage().window().getPosition().getX());
  9.         System.out.println("Y Coordinate: " + driver.manage().window().getPosition().getY());
  10.     }
  11. }
Output:
X Coordinate: 10
Y Coordinate: 10




setPosition():
    The setPosition() method in Selenium Webdriver sets the position of the current window relative to the top left corner of the screen. The Point class instance specifies the target position of the window.

Syntax 1:
  1. Point p = new Point(250, 250);
  2. driver.manage().window().setPosition(p);
Syntax 2:
  1. driver.manage().window().setPosition(new Point(250, 250));

Example:
  1. import org.openqa.selenium.WebDriver;
  2. import org.openqa.selenium.chrome.ChromeDriver;
  3. import org.openqa.selenium.Point;
  4. public class Position {
  5.     public static void main(String[] args) {
  6.         System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
  7.         WebDriver driver = new ChromeDriver();
  8.         driver.get("http://testingcolleges.blogspot.com/");
  9.         Point p = new Point(250,250);
  10.         driver.manage().window().setPosition(p);
  11.     }
  12. }




****

Locators


How to Inspect a web element:
    On every web page, you will find various web elements, and each of these elements is made up of tags, attributes, and values.
    Example: <tag attribute='values'>
  • Right-click any part of the page and Choose Inspect or Shortcut key F12.
  • Select the Element tab (by default it is selected).
  • Note: This inspect tab is called DOM(Document Object Model)
    


What is findElement?
    It is the method to locate elements on the webpage.
What is By?
    By is the mechanism used to locate elements within the document with the help of locator value.
What is a Locator?
    It is an address that identifies web elements within documents with the help of locator value.

Locators: There are eight types of locators.
  1. id
  2. name
  3. XPath
  4. CSS Selector
  5. Class Name
  6. Tag Name
  7. Link Text
  8. Partial Link Text
1. id Locator:
    If an element in your web page has an 'id' attribute, it can be identified using the value of that attribute.

    Syntax (Java): driver.findElement(By.id("id_value"))
    Syntax (C#): driver.FindElement(By.Id("id_value"))
    Syntax (Python): driver.find_element(By.ID, "id_value")

2. name Locator:
    If an element in your web page has a 'name' attribute, it can be identified using the value of that attribute.

    Syntax (Java): driver.findElement(By.name("name_value"))
    Syntax (C#): driver.FindElement(By.Name("name_value"))
    Syntax (Python): driver.find_element(By.NAME, "name_value")

3. XPath Locator:
    XPath is an XML path used for navigation through the HTML structure of the page.
    There are two types of XPath
    1. Absolute XPath
    2. Relative XPath
To learn more about XPath Click Here.

    Syntax (Java): driver.findElement(By.xpath("//xpath"))
    Syntax (C#): driver.FindElement(By.XPath("//xpath"))
    Syntax (Python): driver.find_element(By.XPATH, "//xpath")
Note: we can copy XPath directly from the DOM, Right-Click on the particular element field(on - DOM) then Select copy in and click on Copy XPath.

4. CSS Selector Locator:
    CSS is used to create style rules for web pages and can be used to identify any web element.
To learn how to write CSS Selector Click Here.

    Syntax (Java): driver.findElement(By.cssSelector("value"))
    Syntax (C#): driver.FindElement(By.CssSelector("value"))
    Syntax (Python): driver.find_element(By.CSS_SELECTOR, "value")

5. Class Name Locator:
    If an element in your web page has a 'class' attribute, it can be identified using the value of that attribute.

    Syntax (Java): driver.findElement(By.className("class_value"))
    Syntax (C#): driver.FindElement(By.ClassName("class_value"))
    Syntax (Python): driver.find_element(By.CLASS_NAME, "class_value")

6. Tag Name Locator:
    This Locator is mainly used to get the list of web elements with the particular tag name. We will use this locator very rarely, because here we will assign the values based on the tag, not an attribute. 

    Syntax (Java): driver.findElements(By.tagName("a"))
    Syntax (C#): driver.FindElements(By.TagName("a"))
    Syntax (Python): driver.find_elements(By.TAG_NAME, "a")

7. Link Text Locator:
    Text (Visible Text) used in Hyperlinks can also locate elements.

    Syntax (Java): driver.findElement(By.linkText("text"))
    Syntax (C#): driver.FindElement(By.LinkText("text"))
    Syntax (Python): driver.find_element(By.LINK_TEXT, "text")

8. Partial Link Locator:
    A part of the text(Visible Text) in the Hyperlink can also identify an element.

    Syntax (Java): driver.findElement(By.partialLinkText("text"))
    Syntax (C#): driver.FindElement(By.PartialLinkText("text"))
    Syntax (Python): driver.find_element(By.PARTIAL_LINK_TEXT, "text")




Waits/Synchronization using Selenium with Java


 
Implicit Wait:
    Implicit Wait is used to tell the web driver to wait for a certain amount of time before it throws a "No Such Element Exception".

Before Selenium 4:
Syntax:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Example:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

After Selenium 4:

Syntax/Example:

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








 Explicit Wait:
    Explicit Wait is used to tell the web driver to wait for a certain amount of time before finding the expected web element.

Before Selenium 4:
Syntax:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id="123"]")));
Example:

After Selenium 4:
Syntax:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id="123"]")));




 Fluent Wait:
    Fluent Wait is used 
Before Selenium 4:
Syntax:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                    .withTimeout(40, TimeUnit.SECONDS)
                    .pollingEvery(5, TimeUnit.SECONDS)
                    .ignoring(NoSuchElementException.class);
Example:

After Selenium 4:
Syntax:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                    .withTimeout(Duration.ofSeconds(30))
                    .pollingEvery(Duration.ofSeconds(5))
                    .ignoring(NoSuchElementException.class);
Example:

- Next Page: Take Screen Shot

Using JavaScript Executor in Selenium with Java - part 4

To Clear the History Of the Browser:
Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("history.clear()");







- Next Page: JavaScript FindElements

Using JavaScript Executor in Selenium with Java - part 3




1. Web Page Scroll to a particular element:
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    WebElement ele = driver.findElement(By.id("123"));
                    js.executeScript("arguments[0].scrollIntoView(true);", ele);

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            WebDriver driver = new ChromeDriver();
            JavascriptExecutor js = (JavascriptExecutor) driver;

            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            WebElement src = driver.findElement(By.linkText("Blogger"));
            js.executeScript("arguments[0].scrollIntoView(true);", src);
        }
    }





2. Scroll to the Top:
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    js.executeScript("window.scrollTo(document..body.scrollHeight , 0);");

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            js.executeScript("window.scrollTo(document.body.scrollHeight , 0);");

        }
    }




3. Scroll to the Down:
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    js.executeScript("window.scrollTo(0 , document..body.scrollHeight );");

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            js.executeScript("window.scrollTo(0 , document.body.scrollHeight);");

        }
    }

- Next Page: JavaScript Part 4

Using JavaScript Executor in Selenium with Java - part 2





1. To HighLighting Element
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    WebElement ele = driver.findElement(By.id("123"));
                    js.executeScript("arguments[0].style.border='2px solid red' " , ele);
                    //js.executeScript("Script", Arguments);

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            WebDriver driver = new ChromeDriver();
            JavascriptExecutor js = (JavascriptExecutor) driver;

            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            WebElement src = driver.findElement(By.id("mail"));
            js.executeScript("arguments[0].style.border='2px solid red' " , src);

        }
    }

Output: 






2. Disable a Web Element:  To disable a web element we use the following method.
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    WebElement ele = driver.findElement(By.id("123");
                    js.executeScript("arguments[0].setAttribute('disabled',' ');" , ele);
                    //js.executeScript("Script", Arguments);

    Syntax 2: JavascriptExecutor js = (JavascriptExecutor) driver;
                      js.executeScript("document.getElementById('123').setAttribute('disabled',' '););

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            WebElement FirstName = driver.findElement(By.name("fname"));
            js.executeScript("arguments[0].setAttribute('disabled', ' ');" , FirstName);

        }
    }




3. Disable to Enable:  To enable, the disabled web element we use the following method.
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    WebElement ele = driver.findElement(By.id("123");
                    js.executeScript("arguments[0].removeAttribute('disabled',' ');" , ele);
                    //js.executeScript("Script", Arguments);

    Syntax 2: JavascriptExecutor js = (JavascriptExecutor) driver;
                      js.executeScript("document.getElementById('123').removeAttribute('disabled',' '););

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");
            
            //to disable
            WebElement FirstName = driver.findElement(By.name("fname"));
            js.executeScript("arguments[0].setAttribute('disabled', ' ');" , FirstName);

            //to enable
            js.executeScript("arguments[0].removeAttribute('disabled', ' ');" , FirstName);
        }
    }

- Next Page: JavaScript Part 3

Using JavaScript Executor in Selenium with Java - part 1


    Sometimes, Selenium WebDriver alone will not be able to perform some operations. In that case, by using the JavaScriptExecutor interface we can handle web drivers in the different scenarios as below.
    To run JavascriptExecutor we need to import the package:
    import org.openqa.selenium.JavascriptExecutor;



1. To Perform click operation:
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    WebElement ele = driver.findElement(By.id("123"));
                    js.executeScript("arguments[0].click();" , ele);
                    //js.executeScript("Script", Arguments);

    Syntax 2: JavascriptExecutor js = (JavascriptExecutor) driver;
                      js.executeScript("document.getElementById('123').click();");

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            WebElement btn = driver.findElement(By.id("fem"));
            js.executeScript("arguments[0].click();" , btn);

            // instead of the above two lines we can also write the following line
            //js.executeScript("document.getElementById('fem').click();");
        }
    }





2. To Perform value operation(just like sendKeys()): Fill an element with text in a webpage by executing javaScript.
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    WebElement ele = driver.findElement(By.id("123"));
                    js.executeScript("arguments[0].value='Hello';" , ele);
                    //js.executeScript("Script", Arguments);

    Syntax 2: JavascriptExecutor js = (JavascriptExecutor) driver;
                      js.executeScript("document.getElementById('123').value='Hello';");

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            driver.get("https://testingcolleges.blogspot.com/p/testingform.html");

            WebElement FirstName = driver.findElement(By.name("fname"));
            js.executeScript("arguments[0].value='Testing';" , FirstName);

            // instead of the above two lines we can also write the following line
            //js.executeScript("document.getElementByName('fname')[0].value='Testing';");
        }
    }




3. Creating an Alert box using JavaScript:
    Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
                    js.executeScript("alert('your message');");

Example:
    class JavaScript
    {
        public static void main(String[] args)
        {
            System.setProperty("webdriver.chrome.driver" , "path");
            WebDriver driver = new ChromeDriver();

            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("alert('welcome to Testing Colleges ! ...');");
        }
    }

- Next Page: JavaScript Part 2