Wednesday, 11 September 2013

Selenium Builder | Running selenium scripts on Cloud


Selenium Builder is similar to Selenium IDE. It has special credits like running cross-browser tests on Cloud directly from IDE. Exporting selenium scripts in Java/TestNG/Webdriver combination is feasible on Selenium Builder.

1| Create an account on Sauce and obtain the access key
2| Install the Addon, Selenium Builder in Firefox web browser
3| Open the webpage under test
4| Right click on the page > Launch Selenium Builder
5| Click Selenium 1 | Selenium 2
6| Record selenium scripts
7| Go to 'Run' menu
8| Click 'Run on Sauce OnDemand'
9| Enter the Sauce Username and Access Key
10| Choose the Browser and OS combinations for test execution.



11| Log into Sauce and verify the test results.

Handling Captcha | Webdriver

Make use of the 'input' tag with type 'hidden' in-order to handle Captcha.

Look at this example for reference..


driver.get("http://www.google.com/recaptcha/learnmore");
driver.switchTo().frame(0); //calling iframe with no id
JavascriptExecutor js = (JavascriptExecutor) driver; 
//Setting the captcha values 
js.executeScript("document.getElementsByName('recaptcha_challenge_field')[0].setAttribute('value', '03AHJ_Vuv4tV3FrmUHbImL9JPkWJNqs1KDbFdKfG1jhqa2Uhl4U1vzLxXtZMMkZoAHuVCXA1js3GiaaQJ-zqyuledzZP-PEOV-y_Fx87-U6HVu4nh8kfwPzfPU50yEV5oscb20ptwMGR5EEoAtE8dfAlwCVejJtP779upzfAqn_ID5IQJ2F9Nw218')");
driver.findElement(By.name("recaptcha_response_field")).sendKeys("23129555894");
driver.findElement(By.name("Button1")).click();


Note: setAttribute plays a major role here.

Sunday, 8 September 2013

Handling Windows using AutoIt | Selenium


Configure AutoIt with Selenium script

1| Download AutoIt Full Installation and install
2| Create a new file with extension .au3 | Open a folder Right click > AutoIt v3 Script
3| Right click the file > Edit Script
4| Remove all the scripts (if present)
5| Select Tools > AU3Recorder [record and playback]
6| Select all the 3 check box before recording
7| Press 'Click To Record'
8| After recording, try to edit/remove the function name that starts with an underscore '_' (from script). ie., _AU3RecordSetup()
9| Right click the file > Compile Script
10| An executable file .exe will be generated and ready for integration with Selenium
11| Call the Autoit script, file.exe in Selenium script as shown below,

Runtime.getRuntime().exec("C:\\Users\\Sams\\Desktop\\create.exe");

Note:- 
#1 Install SciTE, SciTE4AutoIt3.exe if the option, AU3Recorder found missing under tools menu.
#2 Sometimes issues like. "The program can't start because MSVCR100.dll is missing from your computer." may appear. Try installing,
Microsoft Visual C++ 2010 Redistributable Package (x86) (or)
Microsoft Visual C++ 2010 Redistributable Package (x64)
based on your machine support for fix.
#3 Autoitscript Functions

Wednesday, 4 September 2013

Keys in Selenium script | Webdriver

Key combinations made easier through Actions. Some of the popular keys were illustrated in this section; Similar key functions can be used for other keys from the image.

Enter/Return
driver.findElement(By.id("Value")).sendKeys(Keys.RETURN);
or|
driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);

#PYTHON
from selenium.webdriver.common.keys import Keys
driver.find_element_by_name("Value").send_keys(Keys.RETURN)
or|
element = driver.find_element_by_id("Value")
element.send_keys("keysToSend")
element.submit()

#RUBY
element = @driver.find_element(:name, "Value")
element.send_keys "keysToSend"
element.submit
or|
element = @driver.find_element(:name, "Value")
element.send_keys "keysToSend"
element.send_keys:return


Down Arrow
driver.findElement(By.id("Value")).sendKeys(Keys.ARROW_DOWN);


TAB
Actions action =new Actions(driver);
action.sendKeys(Keys.TAB).sendKeys("keysToSend");
action.build().perform();

#PYTHON
driver.find_element_by_name("Value").send_keys(Keys.TAB)


Ctrl+End | Scroll to Bottom of the page
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform();


Backspace
Actions actions = new Actions(driver);
actions.sendKeys(Keys.BACK_SPACE).perform();

#PYTHON
driver.find_element_by_name("Value").send_keys(Keys.BACKSPACE)
or|
driver.find_element_by_name("Value").send_keys(Keys.BACK_SPACE)




#PYTHON




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.