Selenium C# Tutorial: Checking an element's attribute values

Updated: Jan 18

Developers are usually configuring various attributes of elements displayed on the web page as part of their design or at runtime to control the style or behavior of elements when they are displayed on the website.


"HTML attributes are special words used inside the opening tag to control the element's behavior. HTML attributes are a modifier of an HTML element type" - Wikipedia

We sometimes need to verify that element attributes are set correctly when creating tests. Using the getAttribute() method of the WebElement class, we can easily retrieve and prove an element's attribute.



How does it work?

By passing the name of the attribute to the getAttribute() method. It returns the value of the attribute as a text. Let's see a small example of getting specific attributes related to the "Google" search window.

The HTML attributes of this window are:

      /*
            <input class="gLFyf gsfi" 
            jsaction="paste:puy29d;" 
            maxlength="2048" 
            name="q" 
            type="text" 
            aria-autocomplete="both" 
            aria-haspopup="false" 
            autocapitalize="none" 
            autocomplete="off" 
            autocorrect="off" 
            autofocus="" 
            role="combobox" 
            spellcheck="false" 
            title="Search" 
            value="" 
            aria-label="Search"
            data-ved="0ahUKEwjTqOa2pOXxAhVSilwKHeKKA9oQ39UDCAQ">
            */ 

Code Example:

IWebDriver chromedriver = new ChromeDriver();
string siteToAccess = "https://www.google.com/";
chromedriver.Navigate().GoToUrl(siteToAccess);
                        
IWebElement test = chromedriver.FindElement(By.Name("q"));
Console.WriteLine(test.GetAttribute("type"));
Console.WriteLine(test.GetAttribute("role"));
Console.WriteLine(test.GetAttribute("name"));            
Console.WriteLine(test.GetAttribute("autocomplete"));
Console.WriteLine(test.GetAttribute("spellcheck"));

Checking an element's CSS values

Various styles are applied to elements displayed in a web application using CSS to have the neat look and usability that customers are looking for. Similar to what we saw in the previous example, we can getCSSValue() method, which returns the value of a specified style attribute.

Code Example:

IWebElement test = chromedriver.FindElement(By.Name("q"));
Console.WriteLine(test.GetCssValue("height"));
Console.WriteLine(test.GetCssValue("color"));


143 views0 comments