Selenium C# Tutorial: Handling Multiple Browser Tabs

The concept of Window Handle remains the same whether a URL is opened in a new window or a new tab. For demonstrating how to handle multiple browser tabs in Selenium C#, we use the test URL as http://the-internet.herokuapp.com/windows The Click Here link on the test page is located using the XPath property. In our earlier articles, we covered XPath in Selenium in greater detail.

Once the button is clicked, the URL http://the-internet.herokuapp.com/windows/new opens up in a new browser tab. The window handle count becomes two with driver.WindowHandles[0] representing window handle of ‘parent window’ and driver.WindowHandles[1] representing window handle of ‘child window’.

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System;
using System.Collections.ObjectModel;
 
namespace Selenium_Window_Demo_1
{
    class Selenium_Window_Demo_1
    {
        IWebDriver driver;
 
        [SetUp]
        public void start_Browser()
        {
            // Local Selenium WebDriver
            driver = new ChromeDriver();
            driver.Manage().Window.Maximize();
        }
 
        [Test, Order(1)]
        public void test_window_ops()
        {
            String test_url = "http://the-internet.herokuapp.com/windows";
 
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
 
            driver.Url = test_url;
 
            var browser_button = driver.FindElement(By.XPath("//a[.='Click Here']"));
            Assert.AreEqual(1, driver.WindowHandles.Count);
 
            string WindowTitle = "The Internet";
            Assert.AreEqual(WindowTitle, driver.Title);
 
            browser_button.Click();
            Assert.AreEqual(2, driver.WindowHandles.Count);
 
            Console.WriteLine("Window Handle[0] - " + driver.WindowHandles[0]);
 
            var newTabHandle = driver.WindowHandles[1];
            Assert.IsTrue(!string.IsNullOrEmpty(newTabHandle));
 
            Console.WriteLine("Window Handle[1] - " + driver.WindowHandles[1]);
 
            Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Url, "http://the-internet.herokuapp.com/windows/new");
 
            string expectedNewWindowTitle = "New Window";
            Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Title, expectedNewWindowTitle);
 
            /* Thread Sleep is not a good practice since it is a blocking call */
            /* Only used for demonstration */
            System.Threading.Thread.Sleep(2000);
 
            driver.SwitchTo().Window(driver.WindowHandles[1]).Close();
            driver.SwitchTo().Window(driver.WindowHandles[0]);
 
            System.Threading.Thread.Sleep(2000);
        }
 
        [TearDown]
        public void close_Browser()
        {
            driver.Quit();
        }
    }
}

The SwitchTo().Window(driver.WindowHandles[0]) is used to switch back to the parent window after closing the child window.

var newTabHandle = driver.WindowHandles[1];
Assert.IsTrue(!string.IsNullOrEmpty(newTabHandle));
 
Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Url, "http://the-internet.herokuapp.com/windows/new");
 
 
string expectedNewWindowTitle = "New Window";
Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Title, expectedNewWindowTitle);
 
/* Thread Sleep is not a good practice since it is a blocking call */
/* Only used for demonstration */
System.Threading.Thread.Sleep(2000);
 
driver.SwitchTo().Window(driver.WindowHandles[1]).Close();
driver.SwitchTo().Window(driver.WindowHandles[0]);

Here are the Window Handles of the two browser windows that were instantiated during automated browser testing:

Selenium WebDriver C# – get text

Below is the example of Html element on the page:

<li id="city" class="anketa_list-item">
   <div class="anketa_item-city">From</div>
    London
</li>

If you want only London by WebDriver?

You could easily get by using class-name

driver.FindElement(By.Class("anketa_item-city")).Text;

or using Xpath

driver.FindElement(By.Xpath("\li\div")).Text;

Get Text Of An Element In Selenium?

Selenium is the most widely used automation testing tool, which reduces human effort and efficiently handles testing the scenarios we encounter every day. One such scenario is how to get the text of an element in Selenium. Selenium offers a getText() method used to get the text of an element, i.e.; it can be used to read text values of an element from a web page.

What Is getText() Method?

The Selenium WebDriver interface has predefined the getText() method, which helps retrieve the text for a specific web element. getText() method in Selenium fetches the inner text of an element, which is not hidden by CSS and returns it as a String value. In simple words, whatever is displayed as text on the browser will be returned as-is by the getText() method. If there is no text corresponding to a web element an empty string is returned.

Let us now begin with the practical application of the getText() method.

Using getText() Method To Get Heading Or Paragraph

We all know that no website is complete without headings or paragraph content. At times it becomes necessary to verify the text on the web page we are landing on. The getText() method in Selenium helps us retrieve a text and do necessary action on it. In the code below, we are reading the heading text from the web page, comparing it with the expected value, and then printing the results.

package getText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
 
public class TextThruHeading {
  	
  	WebDriver driver;
  	
  	@BeforeTest
  	public void setUp(){
  	System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
        	driver = new ChromeDriver();
  	}
  	
  	@Test
  	public void headingText(){
        	driver.get("https://phptravels.com/demo/");
        	driver.manage().window().maximize();
        	String expectedHeading = "APPLICATION TEST DRIVE";
        	
        	//Storing the text of the heading in a string
        	String heading = driver.findElement(By.xpath("//div[@class='text']//h2")).getText();
        	if(expectedHeading.equalsIgnoreCase(heading))
              	System.out.println("The expected heading is same as actual heading --- "+heading);
        	else
              	System.out.println("The expected heading doesn't match the actual heading --- "+heading);
  	}
  	@AfterTest
  	public void tearDown(){
        	driver.quit();
  	}
}

Using getText() Method To Get A Dropdown Text

There are multiple cases when we need to select a specific dropdown value, or maybe get the text values in a dropdown. We can use the getText() method to handle such scenarios as well. We will now see how we can get the values in a dropdown and print the same in the console.

package getText;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public class TextThruDropdown {
 
WebDriver driver;
  	
  	@BeforeTest
  	public void setUp(){
  	  	System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
        	driver = new ChromeDriver();
  	}
  	
  	@Test
  	public void headingText(){
        	driver.get("https://demoqa.com/select-menu");
        	driver.manage().window().maximize();
        	// Working on the third dropdown, viz, Old Style Select menu
        	WebElement drpdn = driver.findElement(By.id("oldSelectMenu"));
        	System.out.println("Clicking on the drop down");
        	Select se = new Select(drpdn);
        	List<WebElement> opt = se.getOptions();
        	System.out.println("The total number of options in the dropdown is : " +opt.size());
        	
        	//Iterate through the list of options
        	System.out.println("The dropdown values are--- ");
        	for(WebElement options : opt){
              	System.out.println(options.getText());
        	}
              	
  	}
  	@AfterTest
  	public void tearDown(){
        	driver.quit();
  	}
}

Using getText() Method To Get Alert Text

Just like the paragraph and dropdown, one can retrieve the text of an alert as well. Alerts are common with many applications, and hence there can be a need to check text present on it. The below code would fetch text from an alert.

package getText;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public class AlertText {
  	WebDriver driver;
  	
        	@BeforeTest
        	public void setUp(){
        	  	System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
              	driver = new ChromeDriver();
        	}
        	
        	@Test
        	public void alertText(){
              	driver.get("https://demoqa.com/alerts");
              	driver.manage().window().maximize();
              	driver.findElement(By.id("confirmButton")).click();
              	String txt = driver.switchTo().alert().getText();
              	System.out.println("The text is - " +txt);
        	}
        	@AfterTest
        	public void tearDown(){
              	driver.quit();
        	}
} 

How To Get Null Or Blank Text Values Using The getText() Method?

There might be cases when your web element doesn’t contain a text value at all. What do you think would happen if we apply the getText() method to such an element? As already told in the beginning, we would get an empty string in return. Let us see an example:

We have picked up the header image, which has no corresponding text, and we will be using the getText() method on the element. You will see an empty string is returned on the console without any error.

package getText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public class NullText {
 
WebDriver driver;
  	
  	@BeforeTest
  	public void setUp(){
  	  	System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
        	driver = new ChromeDriver();
  	}
  	
  	@Test
  	public void headingText(){
        	driver.get("https://demoqa.com");
        	driver.manage().window().maximize();
        	WebElement ele = driver.findElement(By.xpath("//header//img"));
        	System.out.println("The header text is - " +ele.getText());
        	
  	}
  	@AfterTest
  	public void tearDown(){
        	driver.quit();
  	}
}

Difference Between getText() And getAttribute() In Selenium WebDriver

People generally get confused between getText and getAttribute methods a lot. Note that both these methods are entirely different and return different values.

getText() Method

The getText() method returns the visible inner text of a web element. You can refer to any of the above-stated examples to get the idea of getText() method.

getAttribute() Method

On the other hand, getAttribute() method fetches the value of the attribute we wish to retrieve. Let us see the getAttribute() method through a running example:

In the image above, we can see the multiple attributes in the input tag like id, type, class & placeholder. The getAttribute() method will retrieve the value corresponding to the attribute we pass as an argument. Let us see it through code-

package getText;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public class GetAttribute {
        	WebDriver driver;
 
@BeforeTest
public void setUp(){
  	System.setProperty("webdriver.chrome.driver","E:\\Softwares\\chromedriver.exe");
  	driver = new ChromeDriver();
}
 
@Test
public void attributeText(){
  	driver.get("https://www.lambdatest.com/");
  	driver.manage().window().maximize();
// This line would store the attribute value as String variable  	
String attributeValue = driver.findElement(By.id("useremail")).getAttribute("placeholder");
  	System.out.println("The value is - " + attributeValue);
}
@AfterTest
public void tearDown(){
  	driver.quit();
       }    	
}

getText() Method Vs. getAttribute() Method

Suppose we have a following HTML component:

<input name=”Title” type=”text” value=”GoogleTest” />https://www.googletest.com/

Now in this HTML component, if we use getText() method, we will get the value

“https://www.googletest.com/“

// Below code will give https://www.googletest.com/ as output

driver.findElement(By.name(“Title”)).getText();

And if we use getAttribute() method to get the value of attribute “value”, we will get “GoogleTest”.

// Below code will give GoogleTest as output

driver.findElement(By.name(“Title”)).getAttribute(“value”);

Though both of these values are a String value, both of these are entirely different.

Therefore, we mainly use getText() method to get the inner text of an HTML tag and getAttribute() method to get the attribute value of a Placeholder attribute.

We hope you are now clear with how to get text of an element in Selenium and the difference between getText() and the getAttribute() methods and understand which method to use where.