You are on page 1of 9

How to handle dynamic web tables/HTML tables in Selenium webdriver using java?.

Please copy the below is the sample code for Table and make an html file.
<!DOCTYPE html>
<html>
<head>
<style>
tbody {color:red;}
table, th, td { border: 1px solid black;}
</style>
</head>
<body>
<p>Dynamic Table elements</p>
<p><b>Tip:</b> The tbody elements will not affect the layout of the table by def
ault. However, you can use CSS to style these elements.</p>
<table>
<tbody>
<tr>
<td>2014</td>
<td>January</td>
<td>$100</td>
<td>Tk.8000</td>
</tr>
</tr>
<tr>
<td>April</td>
<td>$50</td>
</tr>
<tr>
<td>2015</td>
<td>February</td>
<td>$80</td>
<td>Tk.6400</td>
</tr>
<tr>
<td>March</td>
<td>$60</td>
<td>Tk.4800</td>
</tr>
</tbody>
</table>
</body>
</html>
Java Code

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Dynamictablehandler {
public static void main(String[] a) throws InterruptedException {
// Initialize Web driver
WebDriver driver = new FirefoxDriver();
//Maximize browser window

driver.manage().window().maximize();
//Go to Page
driver.get("file:///F:/table.html");
//get the entire html table and store this in a variable
WebElement table = driver.findElement(By.xpath("html/body/table/tbody"));
//Get all the rows
List<webelement> rows = table.findElements(By.tagName("tr"));
for (int r = 0; r < rows.size(); r++) {
//Get all the columns in every row
List<WebElement> columns = rows.get(r).findElements(By.tagName("td"));
for (int col = 0; col < columns.size(); col++) {
System.out.print(columns.get(col).getText().trim() + " ");
}
System.out.println();
}
driver.quit();
}
}

-----------------------------The Easy way of uploading a file is simple case of just finding the element and
typing the absolute path of the document into it.
It is mandatory that it works only when the textbox is enabled. So please make s
ure that the input element is visible.
Sample HTML Code should look similar to this :
<html>
<body>
<form enctype="multipart/form-data" action="parse_file.php" method="post">
<p>Browse for a file to upload: </p>
<input type="file" name="uploadsubmit">
<br/><br/>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
The following is the example program to upload a file using sendKeys() in seleni
um webdriver without using any third party tools:
package com.easy.upload;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class UploadFile {
static WebDriver driver;
String URL = "application URL";
@Test
public void testUpload() throws InterruptedException
{

driver = new FirefoxDriver();


driver.get(URL);
WebElement element = driver.findElement(By.name("uploadsubmit"))
;
element.sendKeys("D:/file.txt");
driver.findElement(By.name("uploadSubmit"));
String checkText = driver.findElement(By.id("message")).getText(
);
Assert.assertEquals("File uploaded successfully", checkText);
}
}
----------------------Whenever you talk about repository by the name itself you can think that it is k
ind of storage. Object repository is the collection of object and object here is
locator.Object Repository in Selenium Webdriver is quite easy to design so let s
get started.
Here locator means web element id, name, CSS, XPath, class name etc.
Object Repository in Selenium Webdriver
To understand an importance of Object repository, we will take real time scenari
o.
The scenario is you have 100 test cases and in all test cases, you have login sc
enario. If your application changes now and some locator changes like id changes
from email to login email then you have to modify all the test cases and you ha
ve to change the id.

This process does not make any sense so to overcome with this we will move all l
ocator in a separate file and we will link all test cases to this file. In case
any changes happen in our locator we will simply change in that file, not our te
st cases.

This will increase the modularity of test cases and I will strongly suggest that
you should use Object Repository in Automation.
Object Repository in Selenium Webdriver- Selenium Tutorial
Precondition
1- Project should be created and Selenium jars should be added- Click here to co
nfigure .
2- Now create a new file and give file name as Object_Repo (depends on you)with
extension .properties
For this right click on project > create a new file > Specify name
3- Now file is created > Double click on file > File will open in Edit mode
Object repository works on KEY and Value pair so we will specify Keys based on o

ur project and in values we will give locator value.


In below example, I have taken xpath for username,password and loginbutton for f
acebook loginpage.
Key you can write based on your project standard, but value should be correct wh
ich is coming from application
<span style="font-size: 14pt; font-family: arial, helvetica, sans-serif;">facebo
ok.login.username.xpath=.//*[@id='email']
facebook.login.password.xpath=.//*[@id='pass']
facebook.login.Signup.xpath=.//*[@id='loginbutton']</span>
<span style="font-size: 14pt; font-family: arial, helvetica, sans-serif;">import
java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.Test;

public class TestFacebook {


@Test
public void TestOR() throws IOException{
// Specify the file location I used . operation here because
//we have object repository inside project directory only
File src=new File(".Object_Repo.properties");
// Create FileInputStream object
FileInputStream fis=new FileInputStream(src);
// Create Properties class object to read properties file
Properties pro=new Properties();
// Load file so we can use into our script
pro.load(fis);
System.out.println("Property class loaded");
// Open FirefoxBrowser
WebDriver driver=new FirefoxDriver();
// Maximize window
driver.manage().window().maximize();
// Pass application
driver.get("http://www.facebook.com");
// Enter username here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.username.xpath"))).
sendKeys("Selenium@gmail.com");

// Enter password here I used keys which is specified in Object repository.


// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.password.xpath"))).
sendKeys("adsadasdas");
// Click on login button here I used keys which is specified in Object repositor
y.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.Signup.xpath"))).cli
ck();
}
}
</span>
-------------------------------------------------

Page Object Model | POM


Creating Selenium test cases can result in an unmaintainable project. One of the
reasons is that too many duplicated code is used. Duplicated code could be caus
ed by duplicated functionality and this will result in duplicated usage of locat
ors. The disadvantage of duplicated code is that the project is less maintainabl
e. If some locator will change, you have to walk through the whole test code to
adjust locators where necessary. By using the page object model we can make nonbrittle test code and reduce or eliminate duplicate test code. Beside of that it
improves the readability and allows us to create interactive documentation. Las
t but not least, we can create tests with less keystroke. An implementation of t
he page object model can be achieved by separating the abstraction of the test o
bject and the test scripts.
Note: We will follow the same example which we have used in First Test Case. Let s
assume it our base test case and implement the Page Object Model (POM) in it.
How to do it
1. Create a New Package file and name it as pageObjects , by right click on the Proje
ct and select New > Package. We will be creating different packages for Page Obj
ects, Utilities, Test Data, Test Cases and Modular actions. It is always recomme
nded to use this structure, as it is easy to understand, easy to use and easy to
maintain.
2. Create a New Class file and refer the name to the actual page from the test obj
ect, by right click on the above created Package and select New > Class. In our
case it is Home Page and LogIn Page.
3. Now create a Static Method for each Element (Object) in the Home Page. Each m
ethod will have an Argument (driver) and a Return value (element).
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class Home_Page {


private static WebElement element = null;
public static WebElement lnk_MyAccount(WebDriver driver){
element = driver.findElement(By.id("account"));
return element;
}
public static WebElement lnk_LogOut(WebDriver driver){
element = driver.findElement(By.id("account_logout"));
return element;
}
}
Driver is being passed as an Argument so that Selenium is able to locate the ele
ment on the browser (driver).
Element is returned, so that an Action can be performed on it.
Method is declared as Public Static, so that it can be called in any other metho
d without instantiate the class.
Follow the same rule for creating LogIn Page class.
package pageObjects;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LogIn_Page {
private static WebElement element = null;
public static WebElement txtbx_UserName(WebDriver driver){
element = driver.findElement(By.id("log"));
return element;
}
public static WebElement txtbx_Password(WebDriver driver){
element = driver.findElement(By.id("pwd"));
return element;

}
public static WebElement btn_LogIn(WebDriver driver){
element = driver.findElement(By.id("login"));
return element;
}
}
Driver is being passed as an Argument so that Selenium is able to locate the ele
ment on the browser (driver).
Element is returned, so that an Action can be performed on it.
Method is declared as Public Static, so that it can be called in any other metho
d without instantiate the class.
Follow the same rule for creating LogIn Page class.
package pageObjects;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LogIn_Page {
private static WebElement element = null;
public static WebElement txtbx_UserName(WebDriver driver){
element = driver.findElement(By.id("log"));
return element;
}
public static WebElement txtbx_Password(WebDriver driver){
element = driver.findElement(By.id("pwd"));
return element;
}
public static WebElement btn_LogIn(WebDriver driver){
element = driver.findElement(By.id("login"));
return element;
}
}
4) Create a

New Class

and name it as POM_TC by right click on the

automationFramewo

rk Package and select New > Class. We will be creating all our test cases under t
his package.
Now convert your old First Test Case in to the new Page Object Model test case.

package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
// Import package pageObject.*
import pageObjects.Home_Page;
import pageObjects.LogIn_Page;
public class PageObjectModel {
private static WebDriver driver = null;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.store.demoqa.com");
// Use page Object library now
Home_Page.lnk_MyAccount(driver).click();
LogIn_Page.txtbx_UserName(driver).sendKeys("testuser_1");
LogIn_Page.txtbx_Password(driver).sendKeys("Test@123");
LogIn_Page.btn_LogIn(driver).click();
System.out.println(" Login Successfully, now it is the time to Log Off buddy.")
Home_Page.lnk_LogOut(driver).click();
driver.quit();
}
}
You will notice that once you type Home_Page in your test script and the moment
you press dot, all the methods in the Home Page will display. We can expose meth
ods in order to reduce duplicated code. We are able to call these method multipl
e times. This will ensure a better maintainable test code, because we only have
to make adjustments and improvements in one particular place.

You might also like