Selenium C# Tutorial: Locating Web elements using CSS selectors (Advanced)

Updated: Jan 18

Cascading Style Sheets (CSS) is a language used to describe HTML/XML elements (The style of the element and how it is represented on the screen). When using CSS, we can review the pattern–matching (Known as “Selectors”) rules defined for different DOM elements.


For more information about CSS:

https://en.wikipedia.org/wiki/Cascading_Style_Sheets


Selenium WebDriver can use the structure and identifiers of the CSS syntax to locate elements in DOM; this strategy is superior compared to XPath (More reliable and will work faster...).


Finding Element with absolute CSS path

We will use the complete path of the element referring to its hierarchy in the DOM (Same as XPath, any changes made in the element's structure hierarchy will cause failure to locate it using the CSS locator).


CSS Path:

CSS = "#comp-khbyvzuo1label";


Scenario:

  1. Log in to my blog.

  2. Approve the cookie banner,

  3. Navigate the blog section.

Code:

namespace SeleniumC

{

class Program

{

static void Main(string[] args)

{

string CSS = "#comp-khbyvzuo1label";

string cookieApproval = "html body.device-windows div._2svEM._2f7c5._4Ck7e div.HzPhN div._1STS6 button.undefined.MWTAz._6WUOF";

IWebDriver firefoxDriver = new FirefoxDriver();

TEstPreperation(firefoxDriver, cookieApproval);


IWebElement CSSElement = firefoxDriver.FindElement(By.CssSelector(CSS));

CSSAbsolutePath(CSSElement); //CSS absolute path

// driver.Quit();

}


private static void TEstPreperation(IWebDriver webDriver ,string cookie)

{

webDriver.Navigate().GoToUrl("http://www.agilequalitymadeeasy.com/");

Thread.Sleep(3000);

webDriver.FindElement(By.CssSelector(cookie)).Click();

Thread.Sleep(3000);

}


private static void CSSAbsolutePath(IWebElement cssElement)

{

if (cssElement.Displayed)

{

cssElement.Click();

Console.WriteLine("Element is available");

}

else

{

Console.WriteLine("Element is NOT found");

}

}


Finding Element with relative CSS path

We will use the element's relative path instead of its whole hierarchy in the DOM.


CSS Path: "html body.device-windows div#SITE_CONTAINER div#main_MF div#site-root div#masterPage.mesh-layout header#SITE_HEADER_WRAPPER div#SITE_HEADER._11CDm div._2WCQx div._3sXYI div div section#comp-khbyvzcj div._3BQmz div#comp-khbyvzck._1HpZ_ div div wix-dropdown-menu#comp-khbyvzuo._13c26._2cbNh.hidden-during-prewarmup nav#comp-khbyvzuonavContainer.zmzdJ ul#comp-khbyvzuoitemsContainer._3ryjj li#comp-khbyvzuo1._3vxeZ._2TFvc a._25Cim div._3zfdd div p#comp-khbyvzuo1label._3YCIf";


Relative Path: "div p#comp-khbyvzuo1label._3YCIf";


Scenario:

  1. Log in to my blog.

  2. Approve the cookie banner,

  3. Navigate the blog section.


Code:

class Program

{

static void Main(string[] args)

{

string CSS = "div p#comp-khbyvzuo1label._3YCIf";

string cookieApproval = "html body.device-windows div._2svEM._2f7c5._4Ck7e div.HzPhN div._1STS6 button.undefined.MWTAz._6WUOF";

IWebDriver firefoxDriver = new FirefoxDriver();

TEstPreperation(firefoxDriver, cookieApproval);


IWebElement CSSElement = firefoxDriver.FindElement(By.CssSelector(CSS));

CSSRealativePath(CSSElement); //CSS absolute path

// driver.Quit();

}


private static void TEstPreperation(IWebDriver webDriver ,string cookie)

{

webDriver.Navigate().GoToUrl("http://www.agilequalitymadeeasy.com/");

Thread.Sleep(3000);

webDriver.FindElement(By.CssSelector(cookie)).Click();

Thread.Sleep(3000);

}


private static void CSSRealativePath(IWebElement cssElement)

{

if (cssElement.Displayed)

{

cssElement.Click();

Console.WriteLine("Element is available");

}

else

{

Console.WriteLine("Element is NOT found");


}

}



Finding Element with CSS ID

We can locate elements using the ID that was assigned to them; the information that we need is the HTML tag and the element ID (# should set in the middle), Example:


HTML Tag = <button>

Element ID = Approval

Result (Full): (By. cssSelector (“button#Approval”))


Scenario

  1. log-in to Bing.

  2. Add Text into the search field.

Element Details:


CSS By Element ID:

"input#sb_form_q"


Code:

class Program

{

static void Main(string[] args)

{

string CSS = "input#sb_form_q";

string cookieApproval = "html body.device-windows div._2svEM._2f7c5._4Ck7e div.HzPhN div._1STS6 button.undefined.MWTAz._6WUOF";

IWebDriver firefoxDriver = new FirefoxDriver();

TEstPreperation(firefoxDriver, cookieApproval);


IWebElement CSSElement = firefoxDriver.FindElement(By.CssSelector(CSS));

CSSByID(CSSElement); //CSS absolute path

// driver.Quit();

}


private static void TEstPreperation(IWebDriver webDriver ,string cookie)

{

webDriver.Navigate().GoToUrl("https://www.bing.com/");

Thread.Sleep(3000);

//webDriver.FindElement(By.CssSelector(cookie)).Click();

//Thread.Sleep(3000);

}


private static void CSSByID(IWebElement cssElement)

{

if (cssElement.Displayed)

{

cssElement.SendKeys("Test");

Console.WriteLine("Element is available");

}

else

{

Console.WriteLine("Element is NOT found");


}

}


Result:


Finding Element with CSS Class

The CSS selector allows us to search for elements using their class attribute; all we need to do is specify the HTML tag, insert a dot, and add the class attribute.


We can use the same example of the CSS ID, with a minor change of the code:


Code


class Program

{

static void Main(string[] args)

{

string CSS = "input.sb_form_q";

string cookieApproval = "html body.device-windows div._2svEM._2f7c5._4Ck7e div.HzPhN div._1STS6 button.undefined.MWTAz._6WUOF";

IWebDriver firefoxDriver = new FirefoxDriver();

TEstPreperation(firefoxDriver, cookieApproval);


IWebElement CSSElement = firefoxDriver.FindElement(By.CssSelector(CSS));

CSSByClass(CSSElement); //CSS absolute path

// driver.Quit();

}


private static void TEstPreperation(IWebDriver webDriver ,string cookie)

{

webDriver.Navigate().GoToUrl("https://www.bing.com/");

Thread.Sleep(3000);

//webDriver.FindElement(By.CssSelector(cookie)).Click();

//Thread.Sleep(3000);

}


private static void CSSByClass(IWebElement cssElement)

{

if (cssElement.Displayed)

{

cssElement.SendKeys("Test");

Console.WriteLine("Element is available");

}

else

{

Console.WriteLine("Element is NOT found");


}

}


Finding Element with CSS attribute

We can use the CSS locator to search an element using a specific attribute.


Scenario:

  1. Log in to my old blog.

  2. Click on the mail option by:

  3. Single and Multiple attribute selection


[TestMethod]

public void CSSattribute()

{

IWebElement Search;

IWebDriver Firefox = new FirefoxDriver();

Firefox.Navigate().GoToUrl("http://www.machtested.com/");


//Using Single Attribute

Firefox.FindElement(By.CssSelector("input[name='email']")).SendKeys("Text");


//Using Multiple Attributes

Firefox.FindElement(By.CssSelector("input[name='email'][type='text']")).Clear();

}



Finding elements based on partial attribute value

This previous strategy is excellent, but it will not allow us to use it on dynamic elements that change continually. CSS provides another strategy to locate elements based on matching only partial attribute values to overcome this issue.


HTML

<input type="text" placeholder="Email address..." name="email" class="follow-by-email-address">


Code

//Partial matching based on CONTAINS value

Firefox.FindElements(By.CssSelector("input[class*='by-email']"));


//Partial matching based on the START of the attribute value

Firefox.FindElements(By.CssSelector("input[class^='follow']"));


//Partial matching based on the END of the attribute value

Firefox.FindElements(By.CssSelector("input[class$='address']"));


Finding Elements using the attributes name/type

Like the Attribute value strategy, we can perform the exact search on the attribute name (ignoring the attribute value). This strategy is helpful if we need to locate multiple elements with the same attribute name.


Code

//Locate all elements from type input containing the 'type 'attribute

Firefox.FindElements(By.CssSelector("input[type]"));


//Locate all elements from type input that does not contain the 'type 'attribute

Firefox.FindElements(By.CssSelector("input:not([type])"));


Locating elements using text (CSS)

Same as XPath, CSS provides the same strategy where we can find elements using their text;


Example:

WebElement = Firefox.FindElement(By.CssSelector("//a:contains('Quality Assurance')"));


For Firefox:

WebElement = Firefox.FindElement(By.CssSelector("//a[textContent='Quality Assurance']"));



125 views0 comments