August 4, 2013

Get Values from Dropdown (Birthday field in Gmail registration )

August 04, 2013 0
Below is the sample script to get  values or options from a dropdown.

Below is the image of Birth Month dropdown





The Birth Month field is not a Drop down. If you want to get all the values from dropdown first we need to click on the arrow mark and then we can get all the values of dropdown.

Here in the below example..first click on the drop down arrow then all the elements (Month options) will be visible and then you can get all the values of dropdown.
===============================================================
package one;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Gmail_Reg {
public WebDriver driver;

@Before
public void setUp() throws Exception {
//Specify the browser
driver=new FirefoxDriver();
//declare globally wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//maximize the window
driver.manage().window().maximize();
}

@After
public void tearDown() throws Exception {
//close the browser
driver.quit();
}

@Test
public void testGmail_Reg() throws Exception {


driver.get("https://accounts.google.com/SignUp");
//click on the arrow mark
driver.findElement(By.xpath("//label[@id='month-label']/span/div/div")).click();
//get all the vlaues of dropdown
List x=driver.findElements(By.xpath("//div[@class='goog-menu goog-menu-vertical']/div"));
System.out.println("Size of the dropdown : "+x.size());
//print dropdown options
for (int i = 0; i < x.size(); i++) {
System.out.println(x.get(i).getText());
}
Thread.sleep(5000);

}

}
=============================================================

Output:
Size of the dropdown : 12
January
February
March
April
May
June
July
August
September
October
November
December

===================================================================

July 8, 2013

Select Month from Birthday field in Gmail registration page (New UI)

July 08, 2013 13
Below is the Sample script to select month from Gmail Registration page

Below is the image of Birth Month


The Birth Month field is not a Drop down. By using normal select option we can not select a value from that drop down. To select value from these kind of fields. We need to use click command.

Here in the below example..first click on the drop down arrow then all the elements (Month options) will be visible and then click on the option which you want to select.

Below is the sample code


==========================================================
package google;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class gmailReg_birthdaySelect {
    public WebDriver driver;

    @Test
    public void testSelectBirthMonth() {
    }
    @BeforeClass
    public void beforeClass() throws Exception {
        driver = new FirefoxDriver();
        driver.get("https://accounts.google.com/SignUp");

        driver.findElement(By.id("FirstName")).sendKeys("Selenium");
        driver.findElement(By.id("LastName")).sendKeys("Webdriver");
        driver.findElement(By.id("GmailAddress")).sendKeys("seleniumwebdriver");
        driver.findElement(By.id("Passwd")).sendKeys("testingnow");
        driver.findElement(By.id("PasswdAgain")).sendKeys("testingnow");
        //Click on the Arrow mark
        driver.findElement(By.xpath("//label[@id='month-label']/span/div/div")).click();
        //Select value from the list
        driver.findElement(By.xpath("//label[@id='month-label']/span/div[2]/div[@id=':5']")).click();
        driver.findElement(By.id("BirthDay")).sendKeys("16");
        driver.findElement(By.id("BirthYear")).sendKeys("1978");
        driver.findElement(By.xpath("//div[@id='Gender']/div/div")).sendKeys("Male");

    }

    @AfterClass
    public void afterClass() {
        // driver.quit();
    }

}

=============================================================

April 26, 2013

WebDriver Playback in Selenium IDE

April 26, 2013 26
WebDriver Playback in Selenium IDE
Selenium IDE:

As we all know selenium IDE is a plug-in for Firefox and we can record play back in Firefox only but from now on wards we have to modify that statement because test recorded in Firefox can be run in IE and Chrome and other browsers also.


Download the latest version of Selenium IDE (2.9.0)

Below is the Release Notes:


Selenium IDE - Release Notes

  • Enh - Schedule tests for automatic playback at a certain time or periodic intervals. (http://blog.reallysimplethoughts.com/2015/03/09/selenium-ide-scheduler-has-arrived-part-1/)
  • Enh - Allow submission of diagnostic information via a gist.
  • Enh - Improved health logging, including alerts normally hidden.

  • Prerequisites:


    1. Java should be installed in your machine
    2. Download selenium server jar file.

    Set the WebDriver Playback Settings in Selenium IDE

    By default, WebDriver playback is turned off so recording and playback will work as before. To experiment with the WebDriver playback, you need to explicitly turn it on through the WebDriver tab of the Options dialog. To turn on WebDriver playback, check the option Enable WebDriver Playback.
    Then set the Browser to the one you want to use. The choices are android, chrome, firefox, htmlunit, internet explorer, iPhone, iPad and opera.
    Finally restart the Selenium IDE. A restart is required to enable or disable WebDriver Playback. Changing the browser does not require a restart.

    Set up in IDE:

    Part 1:
    1. Open selenium IDE
    2. Go to Options -->Options
    3. Select WebDriver Tab
    4. Check the Enable WebDriver Play back check box
    5. In text box type firefox or internetexplorer or chrome
    6. Click OK
    7. Record a test case in Selenium IDE or open a test case which is already recorded in Selenium IDE.

    Part 2:
    1. Start your selenium server
    2. open comand prompt and navigate to folder where you kept your selenium server and use the below commad to start your selenium server by using below command

    My selenium server jar file is kept in C\Naga\Jar...

    C:\Naga\Jar>java -jar selenium-server-standalone-2.31.0.jar

    Your selenium server will start.

    Then, In Selenium IDE click the run button. Based on the syntax give in options--options---Webdriver your browser will open and will execute the selenium IDE script in that browser.

    Its really awesome feature of Selenium IDE

    For more and detailed description please go through Samit Badle's Blog.

    Below is URL:


    Below are the Limitations:

    Limitations

    This is merely the first step in providing full WebDriver playback. Bugs and limitations are to be expected. I am aware of the following limitations:-
    • Multiple browser windows will be opened and will remain open.
    • Test may not pause or exit on errors.
    • An alert message may pop up for conditions that I have not encountered in my testing.
    • Executing a single command is not yet supported.
    • Highlighting a locator using the Find button may not work.
    • The timeout settings are ignored.
    • Screenshots may not work.
    • User extensions and plugins may not work.
    As you probably know by now, I do not use Selenium IDE myself, so I can only test it a tiny bit. Your help in reporting any issues is always most appreciated.



    NOTE: 
    IF you don't want to use this feature then you need to un check the check box(options--options---Webdriver ) and restart your selenium IDE




    December 31, 2012

    Switch between Frames using webdriver

    December 31, 2012 18
    Switch between Frames using webdriver
    Here is the simple example how to switch between frames.


    There are three ways to switch between frames.

    INDEX:
    Frame(int index)
    Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index "0", the second at index "1" and the third at index "2". Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.

    ID OR NAME:
     frame(java.lang.String nameOrId)
    Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.
    Frame(WebElement frameElement)
    Select a frame using its previously located webelement
    Parameters: frameElement - The frame element to switch to.
    DEFAULTCONTENT()
    Selects either the first frame on the page, or the main document when a page contains iframes.
    Below example explain you how to switch between frames.
    =============================================================
    package testng; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class Frames { public WebDriver driver; @BeforeClass public void beforeClass() { driver=new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Test public void testFrames() throws Exception { driver.navigate().to("http://jqueryui.com/"); driver.findElement(By.linkText("Autocomplete")).click(); //index // driver.switchTo().frame(0); //id or Name //in this example Frame is not having ID or Name so this is invalid here //driver.switchTo().frame("nameorid"); //frameElement driver.switchTo().frame(driver.findElement(By.className("demo-frame"))); //type in text box.. driver.findElement(By.id("tags")).sendKeys("java"); Thread.sleep(5000); //switch back to default content driver.switchTo().defaultContent(); driver.findElement(By.linkText("Accordion")).click(); Thread.sleep(5000); } @AfterClass public void afterClass() { driver.quit(); } }

    December 17, 2012

    Run Webdriver script in Google Chrome

    December 17, 2012 2
    This post explains you how to run your webdriver script in google chrome..

    Firefox Browser:
    driver=new FirefoxDriver();  --it will work and will launch your firefox browser,

    Google Chrome:

    driver= new Chromedriver() --- it will throw an error.

    Error:


    FAILED CONFIGURATION: @BeforeClass beforeClass
    java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list

    To over come this we need to download the chrome driver.exe and we have to specify the apth of chrome driver in the script

    Download path:
    http://code.google.com/p/chromedriver/downloads/list

    take the latest exe file. see the below image




    save the chrome driver in a folder and you need to specify the path of driver in your webdriver script.

    Below is the Sample code:


    package testng;

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;

    public class ChromedriverTest {

    public WebDriver driver;
      @BeforeClass
      public void beforeClass() {
    // Create chrome driver instance...
     System.setProperty("webdriver.chrome.driver", "C:\\xxx\\Jar\\chromedriver.exe");
     driver=new ChromeDriver();
      }


      @Test
      public void testChromedriverTest() throws Exception {
     driver.navigate().to("http://bing.com");
     Thread.sleep(5000);
      }

      @AfterClass
      public void afterClass() {
     driver.quit();
      }

    }


    Use the above code your script will run in google chrome.





    May 22, 2012

    Error while running webdriver tests in IE

    May 22, 2012 4
    While running tests in webdriver using internet explorer i got the following error.

    org.openqa.selenium.WebDriverException: Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information) 

    The reason for this is in Internet Explorer Protected Mode must be set to the same value (enabled or disabled) for all zones. 

    See the below image to understand this line. 

    To handle this error: 

    Go to Internet explorer---Click the setting gear icon----Internet Options---Security Tab



    Check Enable Protected mode for all zones like Local Intranet, Trusted sites and Restricted sites.

    Also, we have to Update the security level to low.

    After doing the above setting you can easily run tests using internet explorer.


    December 29, 2011

    Handling HTTPS sites using Selenium

    December 29, 2011 58
    As all we know selenium is used for automating web application. We will not have any difficulty in automating HTTP site...We face some of the below issues while automating HTTPS sites..

    HTTPS sites will show some security notifications below are some:

    Firefox:



    Internet Explorer:





    To over come this issue we need to add certification

    1. Need to add remote control configuration
    RemoteControlConfiguration rcc = new RemoteControlConfiguration ();

    2. Set TrustAllSSLCertificates flag to TRUE
    rcc.setTrustAllSSLCertificates(true);


    3. Pass the rcc Instance to Selenium Server
    SeleniumServer server = new SeleniumServer(rcc);


    If the above steps also doesnt work you need to install cyber villian certificate to automate HTTPS sites (Especially for IE)


    1. Extract selenium-server.jar
    2. In selenium server folder Open sslSupport folder
    3. It contains cybervillainsCA.cer please install that certificate

    Now you can run your selenium rc  scripts with out any problem for HTTPS sites.


    Below is the code with out the Above steps:


    ====================================

    package selenium;


    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.server.SeleniumServer;

    import com.thoughtworks.selenium.DefaultSelenium;
    import com.thoughtworks.selenium.SeleneseTestCase;

    @SuppressWarnings("deprecation")
    public class HTTPs extends SeleneseTestCase{

    public SeleniumServer ss;
    @Before
    public void setUp() throws Exception
    {
    ss=new SeleniumServer();
    ss.start();
    selenium=new DefaultSelenium("localhost", 4444, "*firefox", "https://www.dibbs.bsm.dla.mil/");
    selenium.start();
    }

    @Test
    public void testSelenium() throws Exception
    {
    selenium.open("/");
    selenium.windowMaximize();

    Thread.sleep(5000);

    }
    @After
    public void tearDown() throws Exception
    {
    selenium.stop();
    ss.stop();
    }

    }
    =============================================
    If you run the above script it will give you an error..see the below image


    To avoid that error please use below code:

    ================================================

    package selenium;


    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.server.RemoteControlConfiguration;
    import org.openqa.selenium.server.SeleniumServer;

    import com.thoughtworks.selenium.DefaultSelenium;
    import com.thoughtworks.selenium.SeleneseTestCase;

    @SuppressWarnings("deprecation")
    public class HTTPs extends SeleneseTestCase{

    public SeleniumServer ss;
    @Before
    public void setUp() throws Exception 
    {
    RemoteControlConfiguration rcc=new RemoteControlConfiguration();
    //trust all ssl certificates
    rcc.setTrustAllSSLCertificates(true);

    ss=new SeleniumServer(rcc);
    ss.start();
    selenium=new DefaultSelenium("localhost", 4444, "*firefox", "https://www.dibbs.bsm.dla.mil/");
    selenium.start();
    }

    @Test
    public void testSelenium() throws Exception
    {
    selenium.open("/");
    selenium.windowMaximize();

    Thread.sleep(5000);

    }
    @After
    public void tearDown() throws Exception 
    {
    selenium.stop();
    ss.stop();
    }

    }


    ========================================================
    The three lines which are in blue will make your browser to trust all SSL certificates..

    Hope this post will be useful..


    December 27, 2011

    Pros and Cons of using Selenium Backed Web driver

    December 27, 2011 1
    Pros and Cons of using Selenium Backed Web driver

    Pros
    1. Allows for the WebDriver and Selenium APIs to live side-by-side
    2. Provides a simple mechanism for a managed migration from the Selenium RC API to WebDriver’s
    3. Does not require the standalone Selenium RC server to be run



    Cons
    1. Does not implement every method
    2. More advanced Selenium usage (using “browserbot” or other built-in JavaScript methods from Selenium Core) may not work
    3. Some methods may be slower due to underlying implementation differences.
    Source:
    http://seleniumhq.org/docs/03_webdriver.html#webdriver-backed-selenium-rc 

    Web Driver Backed Selenium -- Sample script

    December 27, 2011 56
    Web Driver Backed Selenium -- Sample script
    The Java version of WebDriver provides an implementation of the Selenium-RC API. These means that you can use the underlying WebDriver technology using the Selenium-RC API. This is primarily provided for backwards compatablity. It allows those who have existing test suites using the Selenium-RC API to use WebDriver under the covers. It’s provided to help ease the migration path to Selenium-Web driver.


    Sample Backed web driver script looks like this:


    =================================================================



    package webone;


    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebDriverBackedSelenium;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import com.thoughtworks.selenium.SeleneseTestCase;
    import com.thoughtworks.selenium.Selenium;
    @SuppressWarnings("deprecation")
    public class BackedSelenium extends SeleneseTestCase  {

    //web driver --here we are declaring the browser
    WebDriver driver = new FirefoxDriver();
    @Before
    public void setUp() throws Exception {

    String baseUrl = "http://www.google.co.in/";
    selenium = new WebDriverBackedSelenium(driver, baseUrl);
    }


    @Test
    public void testBackedSelenium() throws Exception {
    //This is using selenium
    selenium.open("/");
    selenium.click("id=gbi5");
    selenium.click("id=gmlas");
    selenium.waitForPageToLoad("30000");
    selenium.type("name=as_q", "test");
    //Here we are using Webdriver
    driver.findElement(By.id("as_oq1")).sendKeys("naga");

    driver.findElement(By.id("as_oq2")).sendKeys("Webdriver");
    Thread.sleep(5000);

    }


    @After
    public void tearDown() throws Exception {
    selenium.stop();
    }
    }

    =====================================================

    By using the above format you can use both the Selenium API and Web driver API...



    November 8, 2011

    Screenshot Using Webdriver / Selenium 2.0

    November 08, 2011 4
    Screenshot Using Webdriver / Selenium 2.0
    Hi All,


    Here is a post which explains you how to capture a screenshot using Webdriver/Selenium 2.0

    Its a little bit different from Selenium1/Selenium RC.

    You can see the screen shot in the specified folder (D:\\screenshot)

    Here is the CODE..........

    package scripts;
    import java.io.File;
    import org.apache.commons.io.FileUtils;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class ScreenShot {
    WebDriver driver;

    @Before
    public void setUp() throws Exception {
    driver= new FirefoxDriver();
    }

    @After
    public void tearDown() throws Exception {
    driver.close();
    }
    @Test
    public void testTextBox() throws Exception {
    //open google home page
    driver.get("http://www.google.co.in/");
    // click on options in top right corner
    driver.findElement(By.id("gbi5")).click();
    //click on Advanced Search link
    driver.findElement(By.id("gmlas")).click();
    // type "selenium" in all these words: text box
    driver.findElement(By.name("as_q")).sendKeys("selenium");
    // click on Advanced Search button
    driver.findElement(By.xpath("//input[@type='submit' and @value='Advanced Search']")).click();
    // click on first link from search results
    driver.findElement(By.linkText("Selenium - Web Browser Automation")).click();
    Thread.sleep(5000);
    // below two lines code is to take screenshot
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("D:\\screenshot\\google.png"));
    Thread.sleep(10000);

    }

    }


    Hope it will help you in capturing screenshots....

    Thanks,
    Madhu

    October 5, 2011

    Find XPATH in IE using Java Script

    October 05, 2011 6
    Find XPATH in IE using Java Script
    You might work on some site which are only work in IE..then there are no tools to generate xpath for you........

    You have to write your own xpath to find the element...There are somany tools to identify XPATH in FF..like xpather, firepath and firebug..etc...

    Here is a way to find the XPATH on IE...


    STEPS TO INSTAL BOOKMARKLETS
    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 the 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(node.id!=''){nodeExpr+="[@id='"+node.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.





    I read this article some where...i didnt remenber exactly from where i read this..it is working fine...i tried it..hope it will be useful for guys who are working on IE sites...