Skip to main content

Form - User Input Automation


Text boxes


WebElement t=driver.findElement(By.id(“username”));
t.sendkeys(“test name”);


Buttons

WebElement t=driver.findElement(By.id(“createbutton”));
t.click();


DropDown Boxes 

WebElement select = driver.findElement(By.tagName("select"));
List<WebElement> allOptions = select.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
System.out.println(String.format("Value is: %s", option.getAttribute("value")));
option.click();
}

This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn. As you will notice, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these

Select oSelection = new Select(driver.findElement(By.tagName("select")));
oSelection.deselectAll(); //All options under the select tag are deselected
oSelection.deselectByIndex(index); //Option with mentioned index is deselected
oSelection.deselectByValue(value);//Option with mentioned value is deselected
oSelection.deselectByVisibleText(text);//Option with mentioned text is deselected
select.selectByVisibleText("Edam");//Option with text Edam is selected
select.selectByIndex(index);//Option with mentioned index is selected
select.selectByValue(value);//Option with mentioned value is selected
select.getOptions().size();//returns the number of options in select element
select.getOptions().get(i).getText();//returns the text of the option with index i

Submit Form

Once you’ve finished filling out the form, you probably want to submit it. One way to do this would be to find the “submit” button and click it:

Element.submit();

RadioButton\Checkbox

Radiobuttons and Checkboxes can be handled in the same way. They are identified using the name attribute. The difference between the two is you can select more than one checkbox but you can select only one radio button.

List oRadioButton = driver.findElements(By.name("nameofradiobutton"));

// Create a boolean variable which will hold the value (True/False)
boolean bValue = false;
// This statement will return True, in case of first Radio button is selected
bValue = oRadioButton.get(0).isSelected();
// This will check that if the bValue is True means if the first radio button is selected
if(bValue = true){
// This will select Second radio button, if the first radio button is selected by default
oRadioButton.get(1).click();
System.out.println(oRadioButton.get(i).getAttribute("value"));
}else{
// If the first radio button is not selected by default, the first will be selected
oRadioButton.get(0).click();
}


Actions-Drag and Drop

Here’s an example of using the Actions class to perform a drag and drop. Native events are required to be enabled.

WebElement element = driver.findElement(By.name("source"));

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

(new Actions(driver)).dragAndDrop(element, target).perform();

Actions class supports many actions like moveToElement(),contextClick(),moveByOffset(x,y),click(),doubleclick(),clickAndHold(),release() ,keyDown() and keyUp()also.

build

public Action build()

Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).

Returns:

the composite action
Example:
Actions builder = new Actions(driver); builder.clickAndHold(listItems.get(1)).clickAndHold(listItems.get(2)) .click();
Action selectMultiple = builder.build(); 
selectMultiple.perform();

perform

public void perform()

A convenience method for performing the actions without calling build() first.
Example:
(new Actions(driver)).dragAndDrop(element, target).perform();

WebTable


A webtable is made of table, th, tr ,td values.
Use xpath to point to the table. Xpath can be obtained using developer tools like firebug. Handling tables can be done in three parts. To handle tables you need to understand the concepts of xpath very well.
Part 1 – Location of the table in the webpage </html/body/div[1]/div[2]/div/div[2]/article/div/>

Part 2 – Table body (data) starts from here <table/tbody/>

Part 3 – It says table row 2 and table column 1 <tr[2]/td[1]>

driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[2]/article/div/table/tbody/tr[2]/td[1]")).getText();

For dynamically selecting row and column, use variables.

driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[2]/article/div/table/tbody/tr[“+ srow +”]/td[“ +scol+ ”]")).getText();


String sColValue = "Licensing";

//First loop will traverse through columns

for (int i=1;i<=noofcolumns;i++){

String sValue = null;

sValue = driver.findElement(By.xpath(".//*[@id='post-2924']/div/table/tbody/tr[1]/th["+i+"]")).getText();

if(sValue.equalsIgnoreCase(sColValue)){

// If the sValue match with the description, it will initiate one more inner loop for all the columns of 'i' row
for (int j=1;j<=2;j++){

String sRowValue= driver.findElement(By.xpath(".//*[@id='post-2924']/div/table/tbody/tr["+j+"]/td["+i+"]")).getText();
System.out.println(sRowValue);
}
break;
}
}

Finding number of rows and columns in a webtable
int rowCount=driver.findElements(By.xpath("//table[@id='DataTable']/tbody/tr")).size();
int columnCount=driver.findElements(By.xpath("//table[@id='DataTable']/tbody/tr/td")).size();

The drop down menus or special keyboard actions can be done using Actions class. File upload is not handled in selenium by default. You need AutoIT , another tool to automate that part. We can see it later. 

Comments

Popular posts from this blog

Selenium - Data Driven Testing

In Automation, we need to runs scripts to test the same functionality with different types of data. This data is usually stored in an excel file and accessed via the script to enter in the Application Under Test. In QTP, this is done using the DataTable .  In Selenium we can use the Apache POI API to do read an excel workbook and write the output to the excel file. Using the API is quite simple if you understand the basics. POI  - Poor Obfuscation Implementation. This name was humorously given  because Microsoft code was deliberately made difficult to reverse engineer but still it was reverse engineered. POIFS - Poor Obfuscation Implementation File System. Used to access the input file. HSSF - Horrible Spreadsheet Format This is used to read and write .xls files XSSF - XML Spreadsheet Format This is used to read and write .xlsx files. FileInputStream fs=new FileInputStream("C:\\Users\\Krishna\\selenium workspace\\Data\\firstone.xls"); POIFSFileSyst...

Logging using Apache Log4j

Introduction - Log4j is a brilliant logging API available both on Java and .net framework. - Log4j allows you to have a very good logging infrastructure without putting in any efforts. - Log4j gives you the ability to categorize logs at different levels (Trace, Debug, Info, Warn, Error and Fatal). - Log4j gives you the ability to direct logs to different outputs. For e.g. to a file, Console or a Database. - Log4j gives you the ability to define the format of output logs. - Log4j gives you the ability to write Asynchronous logs which helps to increase the performance of the application. - Loggers in Log4j follow a class hierarchy which may come handy to your applications Log4j consists of five main components - LogManager - Loggers - Appenders - Layouts - Configuration file   Log Manager This is the static class that helps us get loggers with different names and hierarchy. You can consider LogManager as a factory producing logger objects. package Log4jSam...

How to find a WebElement

Find Element & Find Elements Method The difference between “ Find Elemen t” and “ Find Elements ” method is the first returns a WebElement object otherwise it throws an exception and the latter returns a list of WebElements, it can return an empty list if no DOM elements match the query. The “Find” methods take a locator or query object called “ By ”. “ By ” methods are listed below. By ID With this strategy, the first element with the id attribute value matching the location will be returned. If no element has a matching id attribute, a  NoSuchElementException   will be raised. This is the most efficient and preferred way to locate an element, as most of the times IDs are unique. But in some cases UI developers make it having non-unique ids on a page or auto-generating the id, in both cases it should be avoided. Example : If an element is given like this: <input id=”username”></input> WebElement we=driver.findElement(By.id(“username”));  ...