Back To Normal

Subscribe To Our E-Mail Newsletter

Showing posts with label selenium. Show all posts
Showing posts with label selenium. Show all posts

Monday, October 3, 2016

Identifying web element with XPATH


Have details the XPath for representing the web element on a web page.It stands for XML path.We can use fire bug to locate the element by $x(‘’).

Performance problem with Xpath
  Few people consider path is bad , and its slow. And its an mind set of the people. We need to take a call based on the situation. Xpath is highly depend on the structure of the page and its take time to locate the web element on the page.It can easily break when structure of page changes. I personally recommend people to use // instead of /.




Read More


Friday, May 8, 2015

Selenium and Webdriver waits


Here, I have listed all waits methods which is used in selenium web driver. It's helpful to eliminate  the random failures from your test suites.

Implicit waits
Selenium execution will wait for a specified time period to load the DOM elements.After that it will check the presence of web elements in the DOM, if not then throw errors. 
 Example: driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS)

Explicit waits:
Selenium execution will wait for a specified time period to load the locator and it will check the condition every 500ms.
Wait  wait = new WebDriverWait(driver, 30);
WebElement element= wait.until(visibilityOfElementLocated(By.id(“locator")));

Web driver waits 
There is a default web driver waits to check the presence, visibility, clickable and invisible and it will check the condition every 500ms.
Wait  wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
wait.until(ExpectedConditions.elementToBeClickable(locator));
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));

Fluent wait:
If you want to check the presence of the web element in a specific time interval for maximum limit.
  For Example: it waits until the element with id “100" is found. If the element is not found, retry every 5 seconds. But wait only up to a maximum of 60 seconds.
Wait wait = new FluentWait(driver) .withTimeout(60, SECONDS) .pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function() { public WebElement apply(WebDriver driver) { return driver.findElement(By.id("id100")); }

Wait for Ajax calls in capybara. This will helpful to wait until all ajax calls completion.
def wait_for_ajax count = Capybara.default_wait_time * 10 actual_count = 0 count.times do break if page.evaluate_script 'window._ajax_sent == window._ajax_completed' actual_count += 1 sleep 0.1 end fail 'wait_for_ajax timed out! Please check for javascript errors in the context of the test!' if actual_count>= count end
Read More


Saturday, March 7, 2015

Challenges in Webdriver Selenium

Web driver is a library which will allow the user to interact with the browser. Tester always thinks, it's a tool will qualify to automate entire component of web applications.
In general,web driver doesn’t have any libraries to automate all components of web applications.
    Common problems in test automation:
  • Windows objects like save,download,import,export dialog boxes.
  • Switching between windows
  • Web driver doesn’t automate Flash, silver light and charts.
  • Handling Popup/Dialog Windows
  • Handling Hidden objects 
  • Triggering event after setting values.
  • Object Repository or Page object model support.

Handling hidden object and triggering event after setting values.       

         If you are not able to click hidden element on page, then write java script to click the element in browser. I have faced similar issue in my project, after setting value in text box , its not triggering event. Due to that, test were randomly getting failed in CI. When test run in foreground then its getting passed or else failed.      
        I have tried to solve this problem in many ways , using tab keys ,enter keys but nothing worked out. Finally rewritten script in java script to focus out the element after setting values. To click any Hidden element  or event trigger , don’t depend on web driver library better write in java script.    

To click Hidden object      
 JavascriptExecutor js = (JavascriptExecutor)driver;  
 js.executeScript("arguments[0].click();", element);

Trigger event.      
  page.execute_script("$('table.list_price').focusout()”)

Windows objects like save,download,import,export dialog boxes  

        If you are developing and running scripts in windows, then use VBscript ,WSH and Autoit to handle dialog boxes in windows platform. For manipulating excel and handling text files, use VBscript handles.

Switching between windows   
Find details in my previous post: http://automationhints.blogspot.in/2012/05/how-to-identify-popup-window-in.html

Web driver doesn’t automate Flash, silver light and charts. 
 https://code.google.com/p/wipflash/ : Flash based applications
  http://teststack.net/White/ : silver light
  UI Automation : For all .net based applications  

Image comparison : http://www.imagemagick.org/

Object Repository or Page object model support.      
 Java based Framework : PageFactory      
 Ruby on rails : siteprism, capypage.

Read More


Tuesday, September 25, 2012

How to read Excel data by using POI jars

Public List ReadExcel2010(String sFilename)


{

List SheetData = new ArrayList();

InputStream fs = new FileInputStream(filename);

XSSFWorkbook wb = new XSSFWorkbook(fs);

XSSFSheet sheet = wb.getSheetAt(0);

try

{

Header header = sheet.getHeader();
int rowsCount = sheet.getLastRowNum();

System.out.println("Total Number of Rows: " + (rowsCount + 1));

for (int i = 0; i <= rowsCount; i++) {

List data = new ArrayList();

Row row = sheet.getRow(i);

int colCounts = row.getLastCellNum();

System.out.println("Total Number of Cols: " + colCounts);

for (int j = 0; j < colCounts; j++) {

Cell cell = row.getCell(j);

data.add(cell );

System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());

}

Sheetdata.add(data);

}
} catch (Exception ex) {

java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);

} finally {

try {

fs.close();

} catch (IOException ex) {

java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);

}

}
return Sheetdata;

}
Read More


Tuesday, August 21, 2012

Export - Import in Internet Explorer using Selenium Web Driver


Handling Export and Import by using Keys.
WebElement link = driver.findElement(By.xpath("myxpath"));
ExportAndSaveFileInIE(link, Path);

public static void ExportSaveFileInIE(WebElement element,String sFilepath) throws

InterruptedException{
    try {

      Robot robot = new Robot();
       //Focus the Element
       element.sendKeys("");

      //Press Enter Key to populate Window          
      robot.keyPress(KeyEvent.VK_ENTER);
      robot.keyRelease(KeyEvent.VK_ENTER);
   
      //Wait For Dialog        
      Thread.sleep(2000);

     //press s key to save          
      robot.keyPress(KeyEvent.VK_S);
      robot.keyRelease(KeyEvent.VK_S);
      Thread.sleep(2000);
     //press enter to save the file with specified name and in location
     sFilepath = sFilepath.ToUpperCase()
     for (int i=0;i<=sFilepath .length();i++)
     {
      Char ch = sFilepath.ChartAt(i);
      int iascvalue = ch;
      switch(ch)
{
      Case ":"
       robot.keyPress(KeyEvent.VK_SHIFT);
       robot.keyPress(KeyEvent.VK_COLON);
       robot.keyRelease(KeyEvent.VK_COLON);
       robot.keyRelease(KeyEvent.VK_SHIFT);
      Case "\"
    ....
      default
        robot.keyPress(iascvalue );
      robot.keyRelease(iascvalue );
}

     }
     robot.keyPress(KeyEvent.VK_ENTER);
     robot.keyRelease(KeyEvent.VK_ENTER);

 } catch (AWTException e) {

            e.printStackTrace();
  }

Read More


Monday, August 13, 2012

Java : Test Automation Questions and Answers

1. String Immutable
The absolutely most important reason that String is immutable is that it is used by the
class loading mechanism, and thus have profound and fundamental security aspects.

Had String been mutable, a request to load "java.io.Writer" could have been changed to load
"vijay.co.DiskErasingWriter"
Details: http://javarevisited.blogspot.in/2010/10/why-string-is-immutable-in-java.html

2. Two main mehod in single class

Ans : Its possible with different retun type and parameters (method overloading )
3. String Memory allocation vs StringBuffer vs String Builders

String sname ='vijay';

sname ='ragavan';
Details: http://javarevisited.blogspot.in/2011/07/string-vs-stringbuffer-vs-stringbuilder.html

5. Usage of Interface
Often interfaces are touted as an alternative to multiple class inheritance. While
interfaces may solve similar problems, interface and multiple class inheritance are quite
different animals, in particular:
A class inherits only constants from an interface.
A class cannot inherit method implementations from an interface.
The interface hierarchy is independent of the class hierarchy. Classes that implement the
same interface may or may not be related through the class hierarchy. This is not true for
multiple inheritance.

Usage of Interfaces :
You use an interface to define a protocol of behavior that can be implemented by any class
anywhere in the class hierarchy. Interfaces are useful for the following:
Capturing similarities between unrelated classes without artificially forcing a class relationship
Declaring methods that one or more classes are expected to implement
Revealing an object's programming interface without revealing its class. (Objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers.)
6. Garbage collector in java and usage.
Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example, if
an object is holding some non-Java resource such as a file handle or window character font,
then you might want to make sure these resources are freed before an object is destroyed

Keyword: System.gc();
Read More


Thursday, August 2, 2012

How to Clear cookies from internet Explorer by selenium webdriver?:


User can enable Ie capabilities then clear cookies 

DesiredCapabilities caps = DesiredCapabilities.internetExplorer(); caps.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true); WebDriver driver = new InternetExplorerDriver(caps);
driver.manage().deleteAllCookies()

If above one is not woking then U can go for Windows command level clearnace:

RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Java : Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");

Read More


Different Types of drivers in Selenium Web Driver


HtmlUnit Driver
FireFox Driver
Internet ExplorerDriver
Chrome Drivers.

 In details of these drivers , U can go through following links,
  --http://marakana.com/bookshelf/selenium_tutorial/selenium2.html
Read More


Selenium Web driver : Implicit and Explicit Wait

Implicit wait :

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


Explicit Wait: 

Wait<WebDriver> wait = new WebDriverWait(driver, 30);
WebElement element= wait.until(visibilityOfElementLocated(By.id("some_id")));
Read More


Friday, July 27, 2012

Find child elements : Selenium Web driver


When same object is getting duplicated for N number of parent, then user can refer parent and child relationship to identify the object in browser.

WebElement bodyElement = driver.findElement(By.id("body"));
WebElement bodyElement1 = bodyElement.findElement(By.id("body"));
System.out.println(bodyElement1.findElement(By.id("TotalScore")).getText());

User want to read all child elements of div(parent) container by using following methods.

WebElement bodyElement = driver.findElement(By.id("body"));  
List divElements = bodyElement.findElements(By.className("div"));
for(WebElement childDiv : divElements){
 List fieldSetEle = childDiv.findElements(By.tagName("fieldset"));
 System.out.println(childDiv.getTagName()+":"+fieldSetEle.size());
    }  
Read More


Thursday, July 26, 2012

Types of locaters in Selenium Webdriver

Types :  
  • Finding element by id
  • Finding elemeny by name 
  • Finding element by link.
  • Finding element by Xpath.
  • Finding element by CSS
  • Findidng element by DOM
  • Finding child eleme
Finding element by id :

 
For Example : driver.findElement(By.id(userid));

 
Finding elemeny by name :

 
driver.findElement(By.name("logon"));

 
Finding element by link:

 
driver.findElement(By.linkText("rank list"));

 
driver.findElement(By.partialLinkText("rank"));

 
Finding element by Xpath:

 
-- To find xpath user can use fire bug.

 
//table/tr[2]/td/input

 
//input[@id='item_quantity']

 
(//table[@name='cart']//input)[2]

 
//input[contains(@class,'required')]

 
//input[contains(@class,'required') and type='text']

 
some more options..

 
// xpath iposition

 
//Xpath relative

 
Finding element by CSS

 
driver.findElements(By.css("input[class~='required']"));
driver.findElements(By.class("required"));

 
Finding elements by DOM

 
document.forms[0].elements[0]

 
document.forms['loginOut'].elements['username']

 
Read More


Wednesday, May 23, 2012

How to Identify popup window in Selenium Webdriver ?





1. First Check whether its popup window or IFrame window by using IE Developer or Find bug tools.

2. If its popup window then use following code :
driver.findElement(By.xpath("")).click();

Set s=driver.getWindowHandles();

This method will help to handle of opened windows other than parent



Iterator ite=s.iterator();

while(ite.hasNext())

{

String popupHandle=ite.next().toString();

if(!popupHandle.contains(mwh))

{

driver.switchTo().window(popupHandle);

/**/here you can perform operation in pop-up window**

//After finished your operation in pop-up just select the main window again

driver.switchTo().window(mwh);

}

}



This method will help to filter out of all opened windows



1) String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.

WebDriver popup = null;

Iterator windowIterator = browser.getWindowHandles();

while(windowIterator.hasNext()) {

String windowHandle = windowIterator.next();

popup = browser.switchTo().window(windowHandle);

if (popup.getTitle().equals("Google") {

break;

}

}



2) Uncomment code for the same popup,



//action in popup "Google".

popup.findElement(By.name("q")).sendKeys("Thoughtworks");

//action in popup "Google".

popup.findElement(By.name("btnG")).submit();"



3) After the popup actions, switch the driver back to the parent window,



browser.close(); // close the popup.

browser.switchTo().window(parentWindowHandle); // Switch back to parent window.





If its IFrame then use following line.



String parentWindowHandle = driver.getWindowHandle();

driver.switchTo().Frame(driver.findelement(by.id("iframeid")));
// perform ur actions.
//revert back to parent control

driver.switchTo().window(parentWindowHandle);

Read More


Tuesday, April 24, 2012

Select Object from Drop Down : Web driver


Select Object from Drop Down

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

List options = select.findElements(By.tagName("option"));

for(WebElement option : options){

if(option.getText().equals("Name you want"){

option.click();

break;

}
Read More


Friday, April 20, 2012

Web driver For Internet Explorer.

For loading URL:

DesiredCapabilities ieCapabilities = DesiredCapabilities.internerExplorer();
ieCapabilities .setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_INNORING_SECURITY_DDOMAINS)
Read More


How to Create Test suite in Junit ?

import junit.framework.Testcase

public class TestSuite extends Testcase
{
public static Test suite()
{
TestSuite suite = new Testsuite();

suite.addTestSuite(Testcase1.class);

return suite;

}
public static void main (String args[])
{
 TestRunner.run(suite());
}

}
Read More


Wednesday, December 14, 2011

How to connect Webdriver with IE explorer?

Below code will be usefull for you to connect IE with Webdriver.

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

capabilities.set(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);

WebDriver driver = new InternetExplorerDriver(capabilities);


driver.get(sURL);
Read More


How to Integrate Selenium webdriver with eclipse?

1. Create Project in eclipse.


2. Right click the project and select Build Path --> Configure Build Path..

3. Import or Add all external jars to the Libraries .

     1. Add selenium standalone web driver jars

     2. Add Junit jars also..
4. Right click source (src) and create your own pacakges (TestSuite, utilities,Testcases..)

5. Start to write your own testcases in Java..
 public class TestacseName extends Testcase

{

               @setup
               @test
              @teardown

}
6.Run your tetsecase as ..

            1. Right click on Editer and select Run as Junit..

7. It will excuete java code on Browser.
Read More


How to read HtmlTable data by using Selenium Webdriver ?

public void ReadTableData(String sTableID)
{
WebElement table = driver.findElement(By.id(sTableID)));
// Now get all the TR elements from the table

List allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells

for (WebElement row : allRows) {
List cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells) {
Object CellValue = cell.getText();
System.out.Println("Cellvalue" +Cellvalue.toString )
}
}

}


Read More


560 Free Online Courses

Top 200 universities launched 500 free online courses.  Please find the list here .