Saturday, March 23, 2013

Learn Selenium 2 - My First Selenium WebDriver C# Program

Here is a program to go to "https://www.google.com.au" and to search for a text and click on one of the displayed search results.


Following WebDriver name spaces are required for doing many operations

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support;


Program flow

1. An interface driver to access FirefoxDriver is created.


IWebDriver driver = new FirefoxDriver();



2. I have used an implicit wait to give enough time for the selenium to wait for an element to be loaded before doing an action on it.

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));

3. Using methods Navigate().GoToUrl(), specified the address to open in Firefox "https://www.google.com.au"


driver.Navigate().GoToUrl("https://www.google.com.au");



4.Clear the values in input field for entering the search keyword and enter the search keyword.


driver.FindElement(By.Name("q")).Clear();
driver.FindElement(By.Name("q")).SendKeys("Chery Jose");


5. Based on the availability of search buttons displayed in Google either button btnG or btnK is used with and if conditions.


if (driver.FindElement(By.Name("btnK")).Displayed)
   {
      driver.FindElement(By.Name("btnK")).Click();
   }
else if (driver.FindElement(By.Name("btnG")).Displayed)
   {

      driver.FindElement(By.Name("btnG")).Click();
   }


6. Click on a search result you are interested in.


driver.FindElement(By.XPath("//a[@href='http://au.linkedin.c                    om/in/cheryjose']")).Click();



using System;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support;

namespace BusinessCreation
{
    class WaitTimeoutsTimers
    {
            static void Main(string[] args)
            {
                IWebDriver driver = new FirefoxDriver();
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));
                driver.Navigate().GoToUrl("https://www.google.com.au");
                driver.FindElement(By.Name("q")).Clear();
                driver.FindElement(By.Name("q")).SendKeys("Chery Jose");
                if (driver.FindElement(By.Name("btnK")).Displayed)
                {
                    driver.FindElement(By.Name("btnK")).Click();
                 }
                else if (driver.FindElement(By.Name("btnG")).Displayed)
                {

                    driver.FindElement(By.Name("btnG")).Click();
                    driver.FindElement(By.XPath("//a[@href='http://au.linkedin.com/in/cheryjose']")).Click();
                }

            }
    }
}

No comments:

Post a Comment