Selenium Code Snippets -1

I have come across the below question in online forums about  How to click on each google link and get the page title using selenium. Though it is a small task but it involves constructing the xpath at run time and usage of WebDriverBackedSelenium and WebDriver implementation Classes.

Task :
  • Search for the word ‘Selenium’ in google
  • Click on the the link
  • Get the page title 
  • Navigate back and click on another search result
  • Repeat the above until clicking all the search results in the first page   
Here is the code Snippet for the above task 

import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;

public class GoogleLinks {
public static void main(String[] args) {
FirefoxDriver driver = null;
try {
String baseUrl = “”;
driver = new FirefoxDriver();
WebDriverBackedSelenium wbdriver = new WebDriverBackedSelenium(driver,””);
int linkcount = (Integer) wbdriver.getXpathCount(“//ol[@id=’rso’]/li/div/h3/a”);
for (int i = 1; i <= linkcount; i++) {
String Title = driver.findElement(By.xpath(“//ol[@id=’rso’]/li[” + i + “]/div/h3/a”)).getText();
System.out.println(“Clicking on Title :” + Title);
driver.findElement(By.xpath(“//ol[@id=’rso’]/li[” + i + “]/div/h3/a”)).click();
} catch (ElementNotVisibleException enfe) {
System.out.println(“Element Not Visible Exception”);
} catch (ElementNotFoundException enf) {
System.out.println(“Element not found Exception”);
} finally {


Note : You can mail me for your suggestions/discussions.

Excercise : Above Given snippet is for the Firefox browser try the same with the InternetExplorer, Chrome and other available browsers


“We are what we repeatedly do; Excellence,then, is not an act but a habit”



How to get an xpath in IE

if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH.
Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other Firefox add-on.

1) Open IE
2) Type about: blank in the address bar and hit enter
3) From Favorites main menu select—>Add favorites
4) In the Add a favorite popup window enter name GetXPATH1.
5) Click add button in add a favorite popup window.
6) Open the Favorites menu and right click the newly added favorite and select properties option.
7) GetXPATH1 Properties will open up. Select the web Document Tab.
8) Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(!=''){nodeExpr+="[@id='""']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9) Click Ok. Click YES on the popup alert.
10) Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)
11) Repeat steps 6 and 7 for GetXPATH2 that you just created.
12) Enter the following in the URL field for GetXPATH2

javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf(‘@id’)!=-1)break;}currentNode=currentNode.parentNode;}var xpath=”/”+path.reverse().join(‘/’);clipboardData.setData(“Text”, xpath);}o__o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At his point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

Note : hoping that the above post, which i got from google will help you solve finding xpath… to some extent

Selenium Design Patterns By Dima Kovalenko

Recently have gone through the book “Selenium  Design Patterns” by Dima Kovalenko. I would like to summarise few good points from these chapters here.

This book mainly has discussed about some design patterns and best practices to be followed while writing the selenium code for automating the Test Scripts.
1.Chapter One has discussed about the fundamental concepts of how to use the selenium IDE, assertions, comparison, disadvantages and advantages like price, flexibility and Open source. This chapter mainly useful for the newbies to the selenium tool on how to use the Record and Run and view the basic scripts

2.Chapter Two deals with the design patterns. Design Pattern is nothing but a solution to a commonly occurring problem. It is like a template, that can be used in many different situations.

Spaghetti Design Pattern is discussed in this chapter. This pattern is easy to get started as it doesn’t have to have plan ahead. Disadvantage with this pattern is tightly coupled and maintainability is difficult, code duplication

Interesting and important topic of this chapter is Locating of Elements in the Application using different strategies and tools like Inspect Element, Xpath etc.

3.Chapter Three describes about ‘Refactoring Tests‘, which reduces the duplicate code. It is mainly useful when someone implements the code and also helps to reduce the code duplication, it just explained about the importance and how to do it

And finally the last chapter which helps the user on how to set up the selenium with the ruby scripts. This chapter will be much useful to testers, who are interested to Automate the test cases in Ruby, will be much useful.

Eclipse Shortcuts …

Here we have some of the Eclipse Shortcuts Handy…

1. Manage Files and Projects
Ctrl+N Create new project using the Wizard
Ctrl+Alt+n Create new project, file, class, etc.
Alt+f, then . Open project, file, etc.
Ctrl+Shift+r Open Ressource (file, folder or project)
Alt+Enter Show and access file properties
Ctrl+s Save current file
Ctrl+Shift+s Save all files
Ctrl+w Close current file
Ctrl+Shift+w Close all files
F5 Refresh content of selected element with local file system


2. Editor Window
Focus/ cursor must be in Editor Window for these to work.
F12 Jump to Editor Window
Ctrl+Page Down/Ctrl+Page Up Switch to next editor / switch to previous editor
Ctrl+m Maximize or un-maximize current Editor Window (also works for other Windows)
Ctrl+e Show list of open Editors. Use arrow keys and enter to switch
Ctrl+F6/Ctrl+Shift+F6 Show list of open Editors. Similar to ctrl+e but switches immediately upon release of ctrl
Alt+Arrow Left/Alt+Arrow Right Go to previous / go to next Editor Window
Alt+ Open Editor Window Option menu
Ctrl+F10 Show view menu (features available on left vertical bar: breakpoints, bookmarks, line numbers, …)
Ctrl+F10, then n Show or hide line numbers
Ctrl+Shift+q Show or hide the diff column on the left (indicates changes since last save)


3. Navigate in Editor
Home/End Jump to beginning / jump to end of indention. Press home twice to jump to beginning of line
Ctrl+Home/End Jump to beginning / jump to end of source
Ctrl+Arrow Right/Arrow Left Jump one word to the left / one word to the right
Ctrl+Shift+Arrow Down/Arrow Up Jump to previous / jump to next method
Ctrl+l Jump to Line Number. To hide/show line numbers, press ctrl+F10 and select ‘Show Line Numbers’
Ctrl+q Jump to last location edited
Ctrl+./Ctrl+, Jump to next / jump to previous compiler syntax warning or error
Ctrl+Shift+p With a bracket selected: jump to the matching closing or opening bracket
Ctrl+[+]/Ctrl+ on numeric keyboard Collapse / Expand current method or class
Ctrl+[/]/Ctrl+* on numeric keyboard Collapse / Expand all methods or classes
Ctrl+Arrow Down/Ctrl+Arrow Up Scroll Editor without changing cursor position


4. Select Text
Shift+Arrow Right/Arrow Left Expand selection by one character to the left / to the right
Ctrl+Shift+Arrow Right/Arrow Left Expand selection to next / previous word
Shift+Arrow Down/Arrow Up Expand selection by one line down / one line up
Shift+End/Home Expand selection to end / to beginning of line
Ctrl+a Select all
Alt+Shift+Arrow Up Expand selection to current element (e.g. current one-line expression or content within brackets)
Alt+Shift+Arrow Left/Arrow Right Expand selection to next / previous element
Alt+Shift+Arrow Down Reduce previously expanded selection by one step


5. Edit Text
Ctrl+c/Ctrl+x/Ctrl+v Cut, copy and paste
Ctrl+z Undo last action
Ctrl+y Redo last (undone) action
Ctrl+d Delete Line
Alt+Arrow Up/Arrow Down Move current line or selection up or down
Ctrl+Alt+Arrow Up / Ctrl+Alt+Arrow Down/ Duplicate current line or selection up or down
Ctrl+Delete Delete next word
Ctrl+Backspace Delete previous word
Shift+Enter Enter line below current line
Shift+Ctrl+Enter Enter line above current line
Insert Switch between insert and overwrite mode
Shift+Ctrl+y Change selection to all lower case
Shift+Ctrl+x Change selection to all upper case


6. Search and Replace
Ctrl+f Open find and replace dialog
Ctrl+k/Ctrl+Shift+k Find previous / find next occurrence of search term (close find window first)
Ctrl+h Search Workspace (Java Search, Task Search, and File Search)
Ctrl+j/Ctrl+Shift+j Incremental search forward / backwards. Type search term after pressing ctrl+j, there is now search window
Ctrl + Shift + o Open a resource search dialog to find any class


7. Indentions and Comments
Tab/Shift+Tab Increase / decrease indent of selected text
Ctrl+i Correct indention of selected text or of current line
Ctrl+shift+f Autoformat all code in Editor using code formatter
Ctrl+/ Comment / uncomment line or selection ( adds ‘//’ )
Ctrl+Shift+/ Add Block Comment around selection ( adds ‘/… */’ )
Ctrl+Shift+\ Remove Block Comment
Alt+Shift+j Add Element Comment ( adds ‘/** … */’)

minus8. Editing Source Code
Ctrl+Space Opens Content Assist (e.g. show available methods or field names)
Ctrl+1 Open Quick Fix and Quick Assist
Alt+/ Propose word completion (after typing at least one letter). Repeatedly press alt+/ until reaching correct name
Ctrl+Shift+Insert Deactivate or activate Smart Insert Mode (automatic indention, automatic brackets, etc.)

9. Code Information
Ctrl+o Show code outline / structure
F2 Open class, method, or variable information (tooltip text)
F3 Open Declaration: Jump to Declaration of selected class, method, or parameter
F4 Open Type Hierarchy window for selected item
Ctrl+t Show / open Quick Type Hierarchy for selected item
Ctrl+Shift+t Open Type in Hierarchy
Ctrl+Alt+h Open Call Hierarchy
Ctrl+u Find occurrences of expression in current file
Ctrl+move over method Open Declaration or Implementation

minus10. Refactoring
Alt+Shift+r Rename selected element and all references
Alt+Shift+v Move selected element to other class or file (With complete method or class selected)
Ctrl+Shift+c Change method signature (with method name selected)
Alt+Shift+m Extract selection to method
Alt+Shift+l Extract local variable: Create and assigns a variable from a selected expression
Alt+Shift+i Inline selected local variables, methods, or constants if possible (replaces variable with its declarations/ assignment and puts it directly into the statements)


Strength of Character…. “Grit” ?

“We have to be willing to fail, to be wrong, to start over again with lessons learned”.

Are you wondering what is this quotation about ? or looking for more clarity on this ?  Let’s listen to the below video. we will come to know what is the  characteristic emerged as a significant predictor of success and strength of character

Remote Desktop Shortcuts

Some handy Remote Desktop Shortcuts to be helpful :

Shortcut key Description
ALT+PAGE UP Switches between programs from left to right.
ALT+PAGE DOWN Switches between programs for right to left.
ALT+INSERT Cycles through the programs in the order they were started.
ALT+HOME Displays the Start menu.
CTRL+ALT+BREAK Switches the client between full-screen mode and window mode.
CTRL+ALT+END Brings up the Windows Security dialog box.
ALT+DELETE Displays the Windows menu.
CTRL+ALT+MINUS SIGN (-) Places a snapshot of the active window, within the client, on the Remote Desktop Session Host (RD Session Host) server clipboard (provides the same functionality as pressing ALT+PRINT SCREEN on the local computer).
CTRL+ALT+PLUS SIGN (+) Places a snapshot of the entire client windows area on the RD Session Host server clipboard (provides the same functionality as pressing PRINT SCREEN on the local computer).

 Don’t practice until you get it right. Practice until you can’t get it wrong