Sunday 16 March 2014

How to identify the elements using cssSelector in selenium webdriver in C#.Net?

In this article I am going to explain you how we can use cssSelectors to identify the web elements using selenium webdriver in C#.Net.

What is CssSelector in selenium web driver in C#.Net?

cssSelector is used to find the specific element in the given webpage.
Some of the below examples will demonstrate how we can write the cssSelector expressions.

Find all elements with tag input
input
Find all input tag element having  attribute type = ‘hidden’
input[type='hidden']
Find all input tag element having  attribute type = ‘hidden’  and name attribute = ‘ren’
input[type='hidden'][name='ren']
Find all input tag element with attribute type containing ‘hid’
input[type*='hid']
Find all input tag element with attribute type starting with ‘hid’
input[type^='hid']
Find all input tag element with attribute type ending with ‘den’
input[type$='den']

You can find the element containing specific text using below CSS Selector syntax.
$("h3:contains('Cloud')")

Above css will select the element H3 containing text Cloud

How to use cssSelector expressions in selenium web driver in C#.Net?

Below example illustrates how we can use xpath expressions in selenium webdriver in C#.Net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenQA.Selenium;

using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
namespace Abc
{
    class Program
    {
        static void Main(string[] args)
        {

           
IWebDriver driver=null;
try
{
driver = new ChromeDriver(@"F:\selenium\csharp");
driver.Url = "http://www.google.co.in";

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

driver.Navigate();

//we have identified google search box using css selector expression - #lst-ib

driver.FindElement(By.CssSelector("#lst-ib")).SendKeys("Selenium Book in C#");

            }

 catch(Exception e){
 Console.WriteLine("Exception ******"+e.ToString());
               
 }
           
            finally{
            Thread.Sleep(2000);
            driver.Quit();
            Console.ReadLine();
            }

           
        }
    }
}




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

1 comment:

  1. Nice post. Very helpfull. Thanks.

    One question:

    i want to do the following:

    Find all elements with attribute name containing ‘hid’

    Is this the solution:?

    browser.FindElements(By.CssSelector("css=name*='hid']"));

    ReplyDelete

Buy Best Selenium Books

Contributors