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.