Wednesday, 4 September 2013

Xpath Patterns for Locating WebElements


contains()
Elements can also be located using partial text from an attribute value.
i.e., any attribute, class/id has value: say,  'your class is here';  Here, you can make use of contains for locating elements with partial text, 'your class' truncating 'is here'.
1|
//input[contains(@class, 'your partial class')]
2|
//input[contains(text(),'your partial text')]


not(contains())
'not contains'  is just the reverse of  'contains'. 
1|
//input[not(contains(@class, 'your class'))]

Excercise |1|
<ul id="subject">
   <li class="root">
      <a id="abc">"Physics"</a>
   </li>
   <li class="root">
      <a id="abcd">"Chemistry"</a>
   </li>
   <li class="root">
      <a id="abcde">"Mathematics"</a>
   </li>
</ul>

List<WebElement> elements = driver.findElements(By.xpath("//ul[@id='subject']/li[not(contains(.,'Chemistry'))]"));
//driver.findElements(By.xpath("//ul[@id='subject']/li[not(contains(a,'Chemistry'))]")); -Alternate Step
System.out.println(elements.size());

for (int i = 0; i < elements.size(); i++) {
System.out.println(ass.get(i).getText());
}
OUTPUT| 
Physics
Mathematics


text()
The inner text can be used to find Elements.
1|
//input[text()='your text']
2|
//div[contains(text(), 'your text')]


starts-with()
Finds dynamic elements using start of an Element. If your dynamic ids have the format <input id="text-12345" /> where 12345 is a dynamic number you could use the following XPath: //input[starts-with(@id, 'text-')]

Tuesday, 3 September 2013

How to do XPath validation ?


1| Access your web page. e.g., 'http://seleniumworks.blogspot.in/'
2| Press F12 key.
3| Again, press Esc key.
4| Enter your xpath inside $x
$x(your xpath)
e.g.,
$x("//div[@class='navbar section']")
5| Press Enter key for output.


Friday, 30 August 2013

Selenium & Locators


Types of Element Locators:

1| Html id | id attribute
2| Html name | name attribute
3| XPATH
4| Class name
5| CSS Selector
6| Link Text
7| Tag Name


XPATH

XPath is a way to navigate in xml document and this can be used to identify elements in a wen page. You may have to use XPath when there is no name/id associated with element on page or only partial part of name/IDE is constant.

Direct child - /
Relative child - //
id, class, names can also be used with XPath
//input[@name='q']
//input[@id='q']
//input[@class='q']
e.g., By.xpath(“//input[@id=’myElementId’]”)


CSS Selector

CSS location strategy can be used with Selenium to locate elements, it works using cascade style sheet location methods.in which -

Direct child is denoted with - (a space)
Relative child is denoted with - >
id, class, names can also be used with CSS
css=input[name='q']
css=input[id='q'] or input#q
css=input[class='q'] or input.q
e.g., By.cssSelector(“h1[title]”)


Link Text

e.g.,
By.linkText(“your text”)
By.partialLinkText(“your text”)


Note:- If there are constant name/id available, then they should be used instead of XPath and CSS locators. If not, then CSS locators should be given, as their evaluation is faster than XPath in most modern browsers.

Wednesday, 28 August 2013

How to store Left & Top (Location) | Width & Height of an Image/Element using Selenium Webdriver ?


Store width and height of an Image/Element:

int width = driver.findElement(By.id(Value)).getSize().getWidth();
int height = driver.findElement(By.id(Value)).getSize().getHeight();
(or)
System.out.println(driver.findElement(By.id(Value)).getSize());

Store left and top location of an Image/Element:

Point TopLeftlocation =driver.findElement(By.id(Value)).getLocation();
System.out.println(TopLeftlocation.getX() + "\t" + TopLeftlocation.getY());
(or)
Point p = driver.findElement(By.id(Value)).getLocation();
System.out.println("X position:"+p.x);
System.out.println("Y position:"+p.y);
(or)
System.out.println(driver.findElement(By.id(Value)).getLocation());

Page Scroll using Selenium WebDriver


Scroll Down:

import org.openqa.selenium.JavascriptExecutor;
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 250)"); //y value '250' can be altered

Scroll up:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); //x value '250' can be altered

Scroll bottom of the Page:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");
(or)
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform();

Full scroll to bottom in slow motion:

for (int second = 0;; second++) {
        if(second >=60){
            break;
        }
            ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,400)", ""); //y value '400' can be altered
            Thread.sleep(3000);
}
(or)
JavascriptExecutor jse = (JavascriptExecutor)driver;
for (int second = 0;; second++) {
        if(second >=60){
            break;
        }
            jse.executeScript("window.scrollBy(0,800)", ""); //y value '800' can be altered
            Thread.sleep(3000);
}

Scroll automatically to your WebElement:

Point hoverItem =driver.findElement(By.xpath("Value")).getLocation();
((JavascriptExecutor)driver).executeScript("return window.title;");    
Thread.sleep(6000);
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+(hoverItem.getY())+");"); 
// Adjust your page view by making changes right over here (hoverItem.getY()-400)
(or)
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("Value')]")));
(or)
WebElement element = driver.findElement(By.xpath("Value"));
Coordinates coordinate = ((Locatable)element).getCoordinates(); 
coordinate.onPage(); 
coordinate.inViewPort();

Monday, 26 August 2013

Selenium Basics & Tips


1| Maximize Firefox browser window using selenium webdriver

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();

#PYTHON
driver.maximize_window()

#RUBY
require "selenium-webdriver"
@driver.manage.window.maximize



2| Customize browser window size

driver.manage().window().setSize(new Dimension(320, 480));

#PYTHON
driver.set_window_size(1920, 500)

#RUBY
@driver.manage.window.resize_to(300,700)



3| Get current web page URL

System.out.println(driver.getCurrentUrl());

#PYTHON
print driver.current_url

#RUBY
puts @driver.current_url



4| Navigate Back | Forward & Page refresh

Navigate Back
Webdriver driver = new FirefoxDriver();
driver.navigate().back();
or|
Actions actions = new Actions(driver);
actions.sendKeys(Keys.BACK_SPACE).perform();

#PYTHON
driver.back()

#RUBY
@driver.navigate.back


Navigate Forward
driver.navigate().forward();

#PYTHON
driver.forward()

#RUBY
@driver.navigate.forward


Navigate URL
driver.navigate().to("https://www.google.co.in/");

#RUBY
@driver.navigate.to "https://www.google.co.in/"


Page Refresh
driver.navigate().refresh();
or|
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
or|
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("history.go(0)");
or|
driver.navigate().to(driver.getCurrentUrl());
or|
driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
or|
driver.findElement(By.id("filter-box")).sendKeys(Keys.F5);

#PYTHON
driver.refresh()

#RUBY
@driver.navigate.refresh




5| Highlighting Elements

WebElement element1 = driver.findElement(By.className("Value"));
WebElement element2 = driver.findElement(By.id("Value"));
JavascriptExecutor jse = (JavascriptExecutor)driver; 
jse.executeScript("arguments[0].setAttribute('style', arguments[1]);", element1, "color: blue; border: 2px solid blue;");
jse.executeScript("arguments[0].setAttribute('style', arguments[1]);", element2, "color: yellow; border: 0px solid red;");

Excercise|1|
@Test
public void highlighttest() throws Exception {
driver.get("www.whatever.com");
WebElement searchbutton = driver.findElement(By.id("Value"));
highlightElement(searchbutton);
WebElement submitbutton = driver.findElement(By.id("Value"));
highlightElement(submitbutton);
element.click();
}

public void highlightElement(WebElement element) {
for (int i = 0; i < 2; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;");
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
}



6| Multi-Select Elements

Excercise|1|
@Test
public void Multiselect() throws Exception {

driver.get("http://www.ryancramer.com/journal/entries/select_multiple/");

List<WebElement> ele = driver.findElements(By.tagName("select"));
System.out.println(ele.size());
WebElement ele2 = ele.get(0);

List<WebElement> ele3 = ele2.findElements(By.tagName("option"));
System.out.println(ele3.size());

ele2.sendKeys(Keys.CONTROL);
ele3.get(0).click();
ele3.get(1).click();
ele3.get(3).click();
ele3.get(4).click();
ele3.get(5).click();
}


7| Double-click WebElement

Actions action = new Actions(driver); 
action.doubleClick(driver.findElement(By.id("Value"))); 
action.perform();



8| Delete All Cookies

driver.manage().deleteAllCookies();



9| Shortcut to open IDE in the same screen

Ctrl + shift + S






10| Open a New Tab

driver.findElement(By.id("Value")).sendKeys(Keys.CONTROL + "t");
or|
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);



11| Open a New Window

@Test
public void Test01() throws Exception {
openTab("http://www.xyz.com");
}

public void trigger(String script, WebElement element) {
((JavascriptExecutor) driver).executeScript(script, element);
}

public Object trigger(String script) {
return ((JavascriptExecutor) driver).executeScript(script);
}

public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = trigger(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element;
anchor.click();
trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
throw new JavaScriptException(element, "Unable to open Window", 1);
}
}




12| Select Dropdown Box

driver.get("http://www.angelfire.com/fl5/html-tutorial/ddmenu.htm");
Select dropdown = new Select(driver.findElement(By.name("jump")));
dropdown.selectByIndex(1);

Select has more options to play with; Some of the main functions are given below,

dropdown.deselectAll(); // Used while handling multi-select
dropdown.selectByVisibleText("");
dropdown.selectByValue("");
dropdown.deselectByIndex(3);
dropdown.deselectByValue("3");
dropdown.deselectByVisibleText("");



13| Starting Selenium Server

Open cmd. Go to server location and paste the below
$ java -jar selenium-server-standalone-<version-number>.jar



14| All Old versions of IDE available on:

http://release.seleniumhq.org/selenium-ide/


17| Selenium Release Notes [Change_Log]

Check my answer on Stackoverflow:
http://stackoverflow.com/questions/18609557/where-to-find-selenium-webdriver-release-notes/22243556#22243556



18| Right-click WebElement

Actions builder = new Actions(driver);
Action rightClick = builder.contextClick(driver.findElement(By.id("Value"))).build();
rightClick.perform();


Note:-  There will be frequent updates in this section, 'Selenium Basics & Tips'.
#Please comment your thoughts and the topics you need in this blog.

Friday, 5 July 2013

Datadriven + JXL API | TestNG | Method 1

JXL API
Download Jxl.jar

This is one of the Methods I use for Data-driven using Jxl API.  Here, you can perform data driven by creating a reusable library file.

Method 1

Step 1 : Create a library file with all the below mentioned functionality

1. Open Excel Sheet using ExcelSheetPath
2. Read Excel Sheet Row Count
3. Read Cell value from a specified location
4. Create a Dictionary to store Excel Sheet Column name
5. Create a function to read from the Dictionary

The Source code looks like this.


package packagename;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable; 

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelSheetDriver {

// create sheet name
static Sheet wrksheet;
// create workbook name
static Workbook wrkbook =null;
static Hashtable dict= new Hashtable();
//Create a Constructor
public ExcelSheetDriver(String ExcelSheetPath) throws BiffException, IOException
{
//Initialize
wrkbook = Workbook.getWorkbook(new File(ExcelSheetPath));
  
//For Demo purpose the excel sheet path is hardcoded, but not recommended :)
wrksheet = wrkbook.getSheet("Sheet1");
}

//Returns the Number of Rows
public static int RowCount()
{
return wrksheet.getRows();
}

//Returns the Cell value by taking row and Column values as argument
public static String ReadCell(int column,int row)
{
return wrksheet.getCell(column,row).getContents();
}

//Create Column Dictionary to hold all the Column Names
public static void ColumnDictionary()
{
//Iterate through all the columns in the Excel sheet and store the value in Hashtable
for(int col=0;col < wrksheet.getColumns();col++)
{
dict.put(ReadCell(col,0), col);
}
}

//Read Column Names
public static int GetCell(String colName)
{
try {
int value;
value = ((Integer) dict.get(colName)).intValue();
return value;
} catch (NullPointerException e) {
return (0); 
}
} 
}


Next we are going to create actual test file which is going to perform intended operation.

Step 2: Create a TestNG Class file to perform test

Following example perform search by reading values from Excel sheet

Source Code looks like this


package packagename;

import java.io.IOException;
import jxl.read.biff.BiffException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.*;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.thoughtworks.selenium.SeleneseTestCase;

public class className extends SeleneseTestCase {

//Global initialization of Variables
static ExcelSheetDriver xlsUtil;

//Constructor to initialze Excel for Data source
public className() throws BiffException, IOException
{
//Let's assume we have only one Excel File which holds all Testcases. weird :) Just for Demo !!!
xlsUtil = new ExcelSheetDriver("C:\\Data.xls");
//Load the Excel Sheet Col in to Dictionary for Further use in our Test cases.
xlsUtil.ColumnDictionary();
}

private WebDriver driver;

@BeforeTest
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.get("http://www.xyz.com");
}

@Test
public void methodName() throws Exception {

//Create a for loop.. for iterate through our Excel sheet for all the test cases.
for(int rowCnt = 1; rowCnt < xlsUtil.RowCount(); rowCnt++) {

//Enter search keyword by reading data from Excel
driver.findElement(By.id("source Element")).sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("columnName"), rowCnt));
}

}

Create an Excel sheet that resembles this:


Note:- Text highlighted in Orange-color has to modified by User

Tuesday, 2 July 2013

Drag & Drop | Mouse Hover actions [WebDriver]

Drag & Drop Action:

This script allows you to do drag & drop elements; Drag & Drop operations make use of the Actions classes

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(source Element)
.moveToElement(target Element)
.release(target Element)
.build();

dragAndDrop.perform();

(or)
Actions builder = new Actions(driver);
Action dragAndDrop = builder.dragAndDrop(source Elementtarget Element).build();
dragAndDrop.perform();

Mouse Hover Action:

This script allows you to do Mouse Hover elements; Mouse Hover operations make use of the Actions classes

Actions builder = new Actions(driver);

WebElement HoverLink = driver.findElement(By.linkText("
source Element"));
builder.moveToElement(HoverLink);
builder.perform();

Monday, 24 June 2013

Handling switch over from one window to another using Selenium Webdriver

This script helps you to switch over from a Parent window to a Child window and back cntrl to your Parent Window

String parentWindow = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
for(String windowHandle  : handles)
{
if(!windowHandle.equals(parentWindow))
   {
     driver.switchTo().window(windowHandle);
      <!--Perform your operation here for new window-->
driver.close(); //closing child window
    driver.switchTo().window(parentWindow); //cntrl to parent window
    }
}

Tuesday, 4 June 2013

Cross-browser testing on Cloud using Python + RC + Sauce Labs

Generally, cross browser tests are done manually on Browserstack;  We can do the same using Selenium with Python bindings.

Selenium RC: JSON configuration
Sauce-specific settings are given inside Selenium's "browser" parameter. This is generally a string in the form "*browser" (e.g. "*iexplore", "*firefox"), but will now need to be a full JSON object like this:

{
"username": "your username here",
 "access-key": "your access key here",
 "os": "Linux",
 "browser": "firefox",
 "browser-version": "3"
}

Python Code:

#! /usr/bin/env python
#-.- coding=utf8 -.-

from selenium import selenium
import unittest, time, re

class login(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("saucelabs.com",
                                 4444,
                                 """{
                                     "username": "your-sauce-username",
                                     "access-key": "your-access-key",
                                     "os": "Linux",
                                     "browser": "firefox",
                                     "browser-version": "20"
                                 }""",
                                 "http://salesforce.com/")
        self.selenium.start()
        self.selenium.set_timeout(90000)
    
    def test_empty_info(self):
        sel = self.selenium
        sel.open("/in/")
        sel.click("id=button-login")
        sel.wait_for_page_to_load("30000")
        sel.type("id=username", "james")
        sel.type("id=password", "connor")
        sel.click("id=Login")
        sel.wait_for_page_to_load("30000")
        try: self.assertEqual("Your login attempt has failed. The username or password may be incorrect, or your location or login time may be restricted. Please contact the administrator at your company for help.", sel.get_text("css=div.loginError"))
        except AssertionError, e: self.verificationErrors.append(str(e))

     
    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

Note:- Reports are generated as log and video