Wednesday, December 18, 2013

Accessing Different Web Element Using Selenium


Every webpage have many web elements like textbox links,checkbox,list and along with other controls.

Here we try to learn how to access web element  such as like
  • TextBox
  • RadioButton
  • CheckBox
  • ListBox
  • Link
  • Alert
  • IFrame

 1. TextBox

On previous posts we learn how to find the name,class,id,xpath,csspath etc using firebug and firepath.
 
 Here we try to give some value into the inputbox and clear the ipput field.

Entering values in Input Box 

sendKeys() method is used to enter the value into the input boxes.
driver.findElement(By.name("txtbox1")).sendKeys("Test")

Deleting Values in Input Box

clear() method is used to clear the input box.
driver.findElement(By.name("txtbox1")).clear()

Read Input Box value

It is little bit tricky, using getText() doesnot return any dynamically changed value so we need getAttribute() method to get the value or text of this input field. driver.findElement(By.name("txtbox1")).getAttribute("value") 

Check Disabled or ReadOnly InputBox 

 isEnabled() method is used to check the inputbox.

.

       
Example Code
        WebElement element = driver.findElement(By.name("txtbox1"));
        element.sendKeys("Test");

        if (driver.findElement(By.name("txtbox2")).isEnabled()) {
            driver.findElement(By.name("txtbox2")).sendKeys("abcd");
        }
        if (!element.getAttribute("value").isEmpty()) {
            element.clear();
            element.sendKeys("field cleared but again put some value");
        }

2.RadioButton

Toggling on a radio button is done by click().Get the value or text of this radiobutton field we can use getAttribute() method .



Example Code
        List<WebElement> elements = driver.findElements(By.name("radioGroup1"));
             for (WebElement e : elements) {
                 System.out.println(e.getAttribute("value").toString());
                     if (e.getAttribute("value").equals("Radio Button 4 Selected")) {
                         e.click();
            }
        }
 

3.  CheckBox

Toggling checkbox on/off using click() method.Get the value or text of this checkbox field we can use getAttribute() method .We can also verify the checkbox on/off by isSelected() method.



Example Code
        List<WebElement> elements = driver.findElements(By.name("chkbox"));
        for (WebElement e : elements) {
            System.out.println(e.getAttribute("value").toString());
            if (e.getAttribute("value").equals("Check Box 4 Selected")) {
                            if(!e.isSelected()){
                                      e.click();
                            }
            }
        }

 

4.ListBox

A.Single Select List.
B.Multiple Select List.

A.Single Select List


At most one item can be selected in this type of list.

We access this list in two way
1. Import "import org.openqa.selenium.support.ui.Select".
2.Declare the drop-down element as an instance of the Select class. In the example below, we named this instance as “listboxelements”.
3.We can now start controlling “listboxelements” by using any of the available Select methods like:
        listboxelements.selectByIndex(4);
        listboxelements.selectByVisibleText("Item 8");
        listboxelements.selectByValue("Item 7");
4.Get the text value of this selected list by using listboxelements.getFirstSelectedOption().getText()



Example Code
        WebElement dropdownlist = driver.findElement(By.name("dropdownlist"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
        listboxelements.selectByVisibleText("Item 8");
        listboxelements.selectByValue("Item 7");
        System.out.println(listboxelements.getFirstSelectedOption().getText());
or
        WebElement singleSelectDropDown=driver.findElement(By.name("dropdownlist"));
        List<WebElement> dropdownlists = singleSelectDropDown.findElements(By.tagName("option"));
        for (WebElement webElement : dropdownlists) {
            System.out.println(webElement.getText());
                    
            if (webElement.getText().equals("Item 2")) {
                webElement.click();
            }
        }

 

B.Multiple Select List

1.It is same as Single select List
2.We can check the list allow multiple selection or not using isMultiple() method. 
3.Deselect the element we can use this methods like
        listboxelements.deselectAll();
        listboxelements.deselectByIndex();
        listboxelements.deselectByValue();
        listboxelements.deselectByVisibleText();




Example Code
        WebElement dropdownlist = driver.findElement(By.name("multiselectdropdown"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
       
        if (listboxelements.isMultiple()) {
            listboxelements.selectByVisibleText("Item 8");
            listboxelements.selectByValue("Item 4");
        }
       
        if (listboxelements.isMultiple()){
        listboxelements.selectByValue("Item 7");
        }
        listboxelements.deselectAll();
        listboxelements.deselectByIndex(5);
        listboxelements.deselectByValue("Item 8");
        listboxelements.deselectByVisibleText("Item 8");
Or
        WebElement multiSelectDropDown=driver.findElement(By.name("multiselectdropdown"));
        Select options=new Select(multiSelectDropDown);
                    for (WebElement element : options.getOptions()) {
                           if (element.getText().equals("Item 2")) {
                               element.click();
            }
}

5.Link

Links can be accessed using an exact or partial match of their link text. So we can devide this as
A.Exact Link Text
B.Partial Link Text    

both are accessed by using the click() method.

A.Exact Link Text


Accessing links using their exact link text is done through the By.linkText() method.

Keep in Mind:
1.It is case sensitive.
2.Default it take the firstlink



Example Code

        WebElement element = driver.findElement(By.linkText("Google"));
        element.click();

B.Partial Link Text 

Accessing links using a portion of their link text is done using the By.partialLinkText() method.

Keep in Mind:
1.It is case sensitive.
2.Default it take the first matching link.


Example Code

        WebElement element = driver.findElement(By.partialLinkText("Yahoo"));
        element.click();

6.Alert

Basically Java Script alerts are 3 Type.
A.Alert
B.Confirmation
C. Prompt

A.Alert Handling


Normal JavaScript alert can be accepted by using accept() method .Get the text from this alert we use getText() method.

Example Code
        driver.findElement(By.name("alertbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();

B.Confirmation

Confirmation alert can be accepted by using accept() method or to close this alert use dismiss() method.Get the text from this alert we use getText() method.

   

Example Code

         driver.findElement(By.name("confirmbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();
        //myalert.dismiss();

C.Prompt

Prompt alert can be accepted by using accept() method or to close this alert use dismiss() method.Get the text from this alert we use getText() method and enter some text into it we use sendKeys() method


Example Code

        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.sendKeys("Test Prompt Alert JavaScript");
        myalert.accept();
        //myalert.dismiss();

7.IFrame

IFrame is use to show different page  into the same page.Now how to access frames?

1.First Locate the frame name.
2.then use switchTo() method to navigate into the iframe like:

driver.switchTo().frame(1);
driver.switchTo().frame("iframe_b");
driver.switchTo().frame(driver.findElements(By.tagName("iframe")).get(1));

If we need to switch to the parent frame then use :

driver.switchTo().defaultContent();


 


Details code is given below

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package seleniumwebdriver;

/**
 *
 * @author Administrator
 */
import java.util.List;
import java.util.logging.Logger;
import org.openqa.selenium.Alert;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;

/**
 * @author array
 *
 */
public class Test {

    /**
     * @param args
     */
     private static final Logger logger = Logger.getLogger(Test.class.getName());
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        WebDriver driver = new FirefoxDriver();
        driver.get("http://startingwithseleniumwebdriver.blogspot.in/2013/12/frmset1.html");
        // textbox(driver);
        // radioButton(driver);
        // checkBox(driver);
        // singleSelect(driver);
        // multipleSelect(driver);
        // linkCheck(driver);
        // partialLink(driver);
        // clickAlert(driver);
        // clickConfirm(driver);
        // clickPrompt(driver);

        // iFrame(driver);
    }

    public static void textbox(WebDriver driver) {
        WebElement element = driver.findElement(By.name("txtbox1"));
        element.sendKeys("Test");

        if (driver.findElement(By.name("txtbox2")).isEnabled()) {
            driver.findElement(By.name("txtbox2")).sendKeys("abcd");
        }
        if (!element.getAttribute("value").isEmpty()) {
            element.clear();
            element.sendKeys("field cleared but again put some value");
        }

    }

    public static void radioButton(WebDriver driver) {
        List<WebElement> elements = driver.findElements(By.name("radioGroup1"));

        for (WebElement e : elements) {
            System.out.println(e.getAttribute("value").toString());
            if (e.getAttribute("value").equals("Radio Button 4 Selected")) {
                e.click();

            }
        }

    }

    public static void checkBox(WebDriver driver) {
        List<WebElement> elements = driver.findElements(By.name("chkbox"));
        for (WebElement e : elements) {
            System.out.println(e.getAttribute("value").toString());
            if (e.getAttribute("value").equals("Check Box 4 Selected")) {
                if (!e.isSelected()) {
                    e.click();
                }

            }
        }

    }

    public static void singleSelect(WebDriver driver) {
//        WebElement singleSelectDropDown = driver.findElement(By.name("dropdownlist"));
//        List<WebElement> dropdownlists = singleSelectDropDown.findElements(By.tagName("option"));
//        for (WebElement webElement : dropdownlists) {
//            System.out.println(webElement.getText());
//            if (webElement.getText().equals("Item 2")) {
//                webElement.click();
//            }
//        }
        WebElement dropdownlist = driver.findElement(By.name("dropdownlist"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
        listboxelements.selectByVisibleText("Item 8");
        listboxelements.selectByValue("Item 7");
        System.out.println(listboxelements.getFirstSelectedOption().getText());

    }

    public static void multipleSelect(WebDriver driver) {
//                WebElement singleSelectDropDown=driver.findElement(By.name("multiselectdropdown"));
//        Select options=new Select(singleSelectDropDown);
//                    for (WebElement element : options.getOptions()) {
//                        System.out.println(element.getText());
//                           if (element.getText().equals("Item 2")) {
//                element.click();
//            }
//                    }
       
        WebElement dropdownlist = driver.findElement(By.name("multiselectdropdown"));
        Select listboxelements = new Select(dropdownlist);
        listboxelements.selectByIndex(4);
       
        if (listboxelements.isMultiple()) {
            listboxelements.selectByVisibleText("Item 8");
        }
       
        if (listboxelements.isMultiple()){
        listboxelements.selectByValue("Item 7");
        }
        listboxelements.deselectAll();
        listboxelements.deselectByIndex(5);
        listboxelements.deselectByValue("Item 8");
        listboxelements.deselectByVisibleText("Item 8");
       
    }

    public static void linkCheck(WebDriver driver) {
        WebElement element = driver.findElement(By.linkText("Google"));
        element.click();

    }

    public static void partialLink(WebDriver driver) {
        WebElement element = driver.findElement(By.partialLinkText("Yahoo"));
        element.click();
    }

    public static void clickAlert(WebDriver driver) {
        driver.findElement(By.name("alertbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();
       // myalert.dismiss();
       
    }

    public static void clickConfirm(WebDriver driver) {
        driver.findElement(By.name("confirmbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.accept();
        //myalert.dismiss();
   
    }

    public static void clickPrompt(WebDriver driver) {
        driver.findElement(By.name("promptbtn")).click();
        Alert myalert=driver.switchTo().alert();
        System.out.println(myalert.getText());
        myalert.sendKeys("Test Prompt Alert JavaScript");
        myalert.accept();
        //myalert.dismiss();
       
    }

    public static void iFrame(WebDriver driver){
          WebDriver frame =driver.switchTo().frame(driver.findElements(By.tagName("iframe")).get(2));
          frame.switchTo().frame("navbar-iframe");
          frame.findElement(By.name("q")).sendKeys("Test");
          //We switch to iframe 2 from current iframe
          frame.switchTo().defaultContent();
          frame.switchTo().frame(2);
          frame.findElement(By.linkText("Learn HTML")).click();
    }
}

 

1 comment: