Getting the value of a text box from Selenium

This isn’t really a big deal to figure out, but there aren’t a lot of good posts about it so I figured I’d put one up.

Problem
I needed to get the value of a text box from Selenium. My intuition told me that the “Text” property off the IWebElement interface would do it. Nope… it just returns the inner html of the element, which isn’t what you’re looking for in as the value of a text box.

Solution
Use GetAttribute(“value”).

No problem:

Here’s a quick code sample:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://localhost:32616/");

            IWebElement textBox = driver.FindElement(By.Id("testTextBox"));

            // Doesn't work
            string value = textBox.Text;

            // Works
            value = textBox.GetAttribute("value");
        }
    }
}

Hope this helps someone.

Happy coding,

Tom Hundley
Elegant Software Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s