Selenium WebDriver: Working with element's text C#

While testing a web application, one of the basic things that we will need to do is to verify that elements are displayed with their correct values (e.g Names, site, position, etc.).

Selenium WebDriver's WebElement API provides various ways and strategies to retrieve and verify the text of elements, The use of element text is important as sometimes we need to retrieve text or a specific value from an element into a variable at runtime and later use it in other locations in the test flow.

we will retrieve and verify text from an element by using the WebElement class'

.Text property and other interesting properties provide an efficient approach while working with web elements.




Example 1: Validating Site URL

IWebDriver chromedriver = new ChromeDriver();
string siteToAccess = "https://www.agilequalitymadeeasy.com/";
chromedriver.Navigate().GoToUrl(siteToAccess);
            
//Validating Site URL 
if (chromedriver.Url == "https://www.agilequalitymadeeasy.com/")
{
Console.WriteLine("Valid Site URL");  
}
else
{
chromedriver.Quit();
}



Example 2: Validating page title

in this example I want to validate the main page title of my blog:

IWebDriver chromedriver = new ChromeDriver();
string siteToAccess = "https://www.agilequalitymadeeasy.com/";
chromedriver.Navigate().GoToUrl(siteToAccess);
IWebElement pageTitle = chromedriver.FindElement(By.LinkText("DAVID TZEMACH"));
            
//Validating page title 
if (pageTitle.Text == "DAVID TZEMACH")
{Console.WriteLine("Valid Site Title");}
else{chromedriver.Quit();}}

Example 3: Validating the length of a specific text

The page title is "DAVID TZEMACH" meaning that it as 13 chars including a single space. we can easily test it by using the .Text.Length command:

IWebDriver chromedriver = new ChromeDriver();
string siteToAccess = "https://www.agilequalitymadeeasy.com/";
chromedriver.Navigate().GoToUrl(siteToAccess);
IWebElement pageTitle = chromedriver.FindElement(By.LinkText("DAVID TZEMACH"));
Console.WriteLine(pageTitle.Text.Length);


Example 4: Validating the length of a specific text

We can also validate the length of a specific text, this is done by using the ".Text.Length" property.

IWebElement pageTitle = chromedriver.FindElement(By.LinkText("DAVID TZEMACH"));            
if (pageTitle.Text.Length == 13)
{Console.WriteLine("Text length is valid: " + pageTitle.Text.Length);}
else {Console.WriteLine("Text length is wrong: " + pageTitle.Text.Length);}

Example 5: Validating string using Starts/Ends with methods

We can validate the text of an element using the start and end values of the string:

IWebElement pageTitle = chromedriver.FindElement(By.LinkText("DAVID TZEMACH"));            
if (pageTitle.Text.StartsWith("DAVID") && pageTitle.Text.EndsWith("TZEMACH"))
{Console.WriteLine("Text is valid: " + pageTitle.Text);}
else {Console.WriteLine("Text is wrong: " + pageTitle.Text);}