Pages

Wednesday, 24 April 2013

Finding broken images in a page using Selenium Webdriver

What is broken images?

Broken image as the name signifies the web page code refers to an image location(i.e src of the image) is either incorrect or out of date. When you try to search that image at the specified location written in the code you wont be able to find that image.

Reason for broken images :-

There are three possible reasons why your images are not showing up on your pages as expected:
(1) The image file is not located in the same location that is specified in your IMG tag
(2) The image does not have the same file name as specified in your  tag  and 
(3) The image file is either corrupted or damaged.

Code for finding broken images through Selenium :-

WebDriver driver = new FirefoxDriver();
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver (driver);

// Storing all the image elemt  in the variable allImages
List<WebElement> allImages = 
eventFiringWebDriver.findElements(By.tagName("img"));
int countBrokenImages = 0;

// Declaring a dynamic  string of array which will store src of all the broken images
List<String> BrokenimageUrl = new ArrayList<String>();

String script = "return (typeof arguments[0].naturalWidth!=\"undefined\" &&  
arguments[0].naturalWidth>0)";

for (WebElement image : allImages) 
{   
        Object imgStatus = eventFiringWebDriver.executeScript(script, image);          
if(imgStatus.equals(false))
{
String  currentImageUrl = image.getAttribute("src");
String imageUrl = currentImageUrl ;
                BrokenimageUrl.add(imageUrl);
                countBrokenImages++;
         }
}

// Printing the src of the broken images if any
System.out.println("Number of broken images found in the page : " +countBrokenImages);
for (String z : BrokenimageUrl) 
{
    System.out.println(z);
}

Hope the above code resolved your problem.

Monday, 22 April 2013

Adding link text to an element which appears as an image and is not detected by WebDriver

WebDriver not clicking on a link?

Whenever "FirePath" does not detect an element within an anchor tag, which does not have a link text and the element  belongs to an image class, try the below code snippet  for "FirePath" to detect the element and "WebDriver" to click on the element.

Approach:
- One has to remove the class tag from the element so that it does not behave as an image anymore.
- The innerHTML has to be edited and a link text has to be appended to the element so that it can be recognized for further actions.

Code Snippet :

public static void replaceLinkIdentifier(WebDriver driver, By locator, String replace_id){
   //Replacing link identifier
    JavascriptExecutor js = (JavascriptExecutor) driver;
    WebElement element= driver.findElement(locator);
    js.executeScript("arguments[0].setAttribute('class', arguments[1]);",element, ""); //Setting the class attribute to null, so that the element does not behave as an image.
    js.executeScript("arguments[0].setAttribute('id', arguments[1]);",element, replace_id);  //Substituting/Adding an id for future reference.
     String el = element.getAttribute("id");
    js.executeScript("var t ="+el+";t.innerHTML+='"+replace_id+"';", ""); //Adding the visible link text which is same as id.
    }

The above code snippet would remove the image class from the element and add the link text, same as the 'replace_id' provided here.
After which the element could be acted upon, with reference to the id set in the snippet, which is same as the 'replace_id' here.


Hope the trick helped .

Monday, 25 March 2013

Selenium : Get Date and Time of a specific timezone

Have we come across such a situation where we need to fetch Server date and time which is located in US/Canada/Russia/French etc. and do some activities with that in Selenium.

If yes, you are just in the right place as we are going to discuss something similar which will help us fetch date and time particular to a specific timezone. We will use 2 built-in java classes in order to satisfy our need :-

  1. Date - It represents a specific instant in time, with millisecond precision.
  2. SimpleDateFormat - It's a concrete class for formatting and parsing dates in a locale-sensitive manner.


Code snippet to use :-


// Locale date and time
Date date = new Date();  
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
        
// Get US/Eastern time
formatter.setTimeZone(TimeZone.getTimeZone("US/Eastern")); 
// Prints the date in the US timezone  
System.out.println("US/Eastern date & time : " +formatter.format(date));  
        

// Set the formatter to use a different timezone  
formatter.setTimeZone(TimeZone.getTimeZone("IST"));  
// Prints the date in the IST timezone  
System.out.println("India date & time : " +formatter.format(date));


How to get all available Time-zones?


// To get all available Time-zones
String[] allTimeZones = TimeZone.getAvailableIDs();   
for (int i = 0; i < allTimeZones.length; i++) 
{  
    System.out.println(allTimeZones[i]); 
}

Hope it helps!! :D

Wednesday, 20 March 2013

Deal with Multiple Scroller inside a Webpage using Selenium

In our Automation journey, we may come across situations where we need to scroll a specific webpage or web element to traverse through contents present inside. In Selenium, we don't have any Pre-defined/built-in method for that, but we can introduce JavaScript methods to satisfy our automation needs. Please go through the examples written below to get an idea on how to do that -

Deal with Scroller present within a Web Page :


WebDriver webDriver = new FirefoxDriver();
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver();
eventFiringWebDriver.executeScript("scroll(<pixel-to-scroll-in-horizontal>,<pixel-to-scroll-in-vertical>)");

Note - <pixel-to-scroll-in-horizontal> and <pixel-to-scroll-in-vertical> should be the number of pixel we want to scroll through in horizontal and vertical respectively. 
For example, if we want to scroll through 100 pixels in horizontal and 200 pixels in vertical, we need to declare :

eventFiringWebDriver.executeScript("scroll(100,200)");



Deal with Scroller present within a Web Element :


WebDriver webDriver = new FirefoxDriver();
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver();
eventFiringWebDriver.executeScript("document.getElementById('<id-of-the-webelement>').scrollTop = <pixel-to-scroll>");

Note - <pixel-to-scroll> should be the number of pixel we want to scroll through. 
For example, if we want to scroll through 200 pixels, we need to declare :

eventFiringWebDriver.executeScript("document.getElementById('<id-of-the-webelement>').scrollTop = 200");


Tuesday, 20 November 2012

Running local script in remote machine

How to run the local script in remote machine?
In manual testing we often used to do cross browser testing. The same thing we can do by automation using selenium webdriver. Followings are some steps to run  a local script in a remote machine.

Steps:
1. Download "selenium-server-standalone-2.*.jar" in the remote machine. Download from here
(If this jar is deprecated please try for a new jar.Just type selenium standalone jar for web driver in Google for new jar)
Note: Download the jar file in remote machine not in the local machine.

2. Open the command prompt in the remote machine and run the following command "java -jar < downloaded jar filepath>". This command will run a selenium server. If it will not able to run the selenium server, please just open this link in browser and click on  "okk".
Note: Be sure that java has been installed in the client machine. If not installed please install java first.

3. Then run the following java code from the machine from which you are going to initiate the remote machine.
import java.io.File;
import java.net.URL;
import org.openqa.selenium.OutputType;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class RemotelyRunningScript {
public static void main(String s[]) throws Exception {
System.out.println("coming to this only");
URL url = new URL( "http", "local host", 4444, "/wd/hub" );
DesiredCapabilities capabilities =DesiredCapabilities.firefox();
System.out.println("1");
capabilities.setJavascriptEnabled(true);
System.out.println("2");
WebDriver driver = new RemoteWebDriver(url,capabilities);
System.out.println("4");
driver.get("http://www.yahoo.com");
//File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//FileUtils.copyFile(scrFile, new File("c:\\screenshot\\googlesearch-webdriverapi.png"));
System.out.println("opened yahoo page succesfully");
driver.quit();
}
}

Note: In place of "local host" please provide the remote IP. e.g. 192.145.12.45



Monday, 19 November 2012

Take Screenshot using Selenium Webdriver

Why Screenshot is required ?
While doing manual testing we often need to take the screenshot in case we come up with any issue. We can do the same thing for the Automation testing as well. While running a script there might be a chance of fail of the script. So in that case we have to take the screen shot for that failed script in order to report as an issue.
I am giving a simple example how to take the screenshot after opening "google.com" in firefox browser :-

     1. WebDriver driver = new FirefoxDriver(); // Opening the Firefox browser       
      2. driver.get("http://www.google.com/");
      3. File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // This
          will take the screen shot and will store in srcFile file.
      4. FileUtils.copyFile(scrFile, new File("File Path Location")); // Here you can change the
           path location you want.

Note : File path should contain the file name at the end. e.g. : c:\\temp\\screenshot.png.

After executing the code :
Just go to the path specified and you will able to find a screenshot.


Tuesday, 26 June 2012

Verify Tool-tip text in Selenium

A tool-tip is small rectangular pop-up window that appears near an object in a graphical user interface (GUI) on mouse hovering that object. Tool-tip contains a brief text message identifying or explaining the object.

GoogleTooltip

                                                   Fig : Tool-tip for the Google logo

In Selenium we sometime need to verify tool-tips present in web pages to satisfy our automation needs. This post is dedicated towards how to automate this scenario through Selenium.


Get the Tool-tip text through Selenium Webdriver :-

To get the tool-tip text of a particular object we need to mouse hover the object. Through selenium we can automate the same. Just use the following selenium webdriver code to get the tool-tip text :
  1. WebDriver driver = new FirefoxDriver();
  2. Actions ActionChains = new Actions(driver);
    'Actions' class is used to generate a sequence of actions.
  3. WebElement toolTipObject = driver.findElement(By.xpath("//*[@id='hplogo']"));
  4. ActionChains.clickAndHold(toolTipObject).perform(); 'clickAndHold' method is used to mouse hover a particular object on the web page.


Verify Tool-tip text through Selenium :-

To verify tool-tip present for an object, we first have to locate the object on the page and the appropriate html 'tag-attribute' describing the tip. We have two popular tag-attribute through which tool-tips can be given for a particular object :
  1. 'alt' html tag-attribute. Example : 
  2. 'title' html tag-attribute. Example : <div id="object" title="Tool-tip for object">
To verify tool-tip, we have to access any one of the two tag-attributes through Selenium. 

A) Selenium IDE :
In Selenium IDE, we have a command called 'storeAttribute' through which we can store the value of a particular attribute present under a html tag. For tool-tip, we can store the value of 'alt' or 'title' tag in a variable by using 'storeAttribute' command which can be verified against the expected value of the tool-tip.
Example (Tool-tip for the Google logo) :
Command : storeAttribute
Target : id=hplogo@title
[id=hplogo - is the locator for the tool-tip object (Here, locator for the Google logo present on the page). title - is the tag-attribute]

Value : GoogleTooltip
[Name of the variable which stores the value of the tool-tip]



B) Selenium RC :
Selenium RC uses 'getAttribute' method which serves same purpose as 'storeAttribute' command in Selenium IDE.
Example (Tool-tip for the Google logo) :
  1. selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.co.in/");
  2. selenium.start();
  3. selenium.open("/");
  4. String GoogleTooltip = selenium.getAttribute("id=hplogo@title");
    [id=hplogo - is the locator for the tool-tip object (Here, locator for the Google logo present on the page). title - is the tag-attribute].
     
'GoogleTooltip' is the variable stores the value of the tool-tip.


C) Selenium Webdriver :
Selenium Webdriver also uses 'getAttribute' method to store the attribute value of a html tag.
Example (Tool-tip for the Google logo) :
  1. WebDriver driver = new FirefoxDriver();
  2. WebElement toolTipObject = driver.findElement(By.xpath("//*[@id='hplogo']"));
  3. String GoogleTooltip = toolTipObject.getAttribute("title");
'GoogleTooltip' is the variable stores the value of the tool-tip for the 'toolTipObject' object.