We can retrieve the text from an input box in Selenium using the getAttribute() method. Specifically, the value entered in a text field can be obtained by fetching the value attribute of the WebElement.
Below, we have provided example scripts that demonstrate how to fetch text from an input box using Selenium in Java, C#, and JavaScript.
getattribute
-
Java with TestNG
-
C# with NUnit
-
JavaScript – with Mocha
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class GetAttributeInputTest {
WebDriver driver;
@BeforeClass
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com"); // Replace with your URL
}
@Test
public void fetchTextFromInputBoxUsingGetAttribute() {
// Locate input box
By inputBox = By.id("searchBox"); // Replace with actual locator
// Enter text
driver.findElement(inputBox).sendKeys("Selenium TestNG");
// Fetch text using getAttribute("value")
String actualValue = driver.findElement(inputBox).getAttribute("value");
// Print and verify
System.out.println("Fetched value from input box: " + actualValue);
Assert.assertEquals(actualValue, "Selenium TestNG");
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumTests
{
public class GetAttributeInputTest
{
IWebDriver driver;
[SetUp]
public void Setup()
{
driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://example.com"); // Replace with your URL
}
[Test]
public void FetchTextFromInputBoxUsingGetAttribute()
{
IWebElement inputBox = driver.FindElement(By.Id("searchBox")); // Replace locator
inputBox.SendKeys("Selenium NUnit");
string actualValue = inputBox.GetAttribute("value");
TestContext.WriteLine("Fetched value: " + actualValue);
Assert.AreEqual("Selenium NUnit", actualValue);
}
[TearDown]
public void TearDown()
{
driver.Quit();
}
}
}
const { Builder, By } = require('selenium-webdriver');
const assert = require('assert');
describe('GetAttribute Input Test', function () {
this.timeout(30000);
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
await driver.manage().window().maximize();
await driver.get('https://example.com'); // Replace with your URL
});
it('Fetch text from input box using getAttribute', async function () {
const inputBox = await driver.findElement(By.id('searchBox')); // Replace locator
await inputBox.sendKeys('Selenium JavaScript');
const actualValue = await inputBox.getAttribute('value');
console.log('Fetched value:', actualValue);
assert.strictEqual(actualValue, 'Selenium JavaScript');
});
after(async function () {
await driver.quit();
});
});