How to get title of webpage in selenium

In Java and JavaScript, the page title is obtained using the getTitle() method, whereas in C#, it is accessed using the Title method of the WebDriver instance. This method returns the title of the current web page as a String. We can verify the actual page title of the web page with expected title using Assertions.

Below, we have provided example scripts that demonstrate how to get the web page title using Selenium in Java, C#, and JavaScript.

getTitle of webpage

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class GetPageTitle {

@Test
public void verifyTitle() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");

String expTitle = "Google";
String actualTitle = driver.getTitle();

Assert.assertEquals(actualTitle, expTitle);

driver.quit();
}
}

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;

class GetPageTitle
{
[Test]
public void verifyTitle()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.google.com");

string expTitle = "Google";
string actualTitle = driver.Title;

Assert.AreEqual(expTitle, actualTitle);

driver.Quit();
}
}

const { Builder } = require("selenium-webdriver");
const assert = require("assert");

(async function getPageTitle() {
let driver = await new Builder().forBrowser("chrome").build();

await driver.get("https://www.google.com");

let expTitle = "Google";
let actualTitle = await driver.getTitle();

assert.strictEqual(actualTitle, expTitle);

console.log("Page Title:", actualTitle);

await driver.quit();
})();

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x