Selenium locator for <label for="x">

Johan Levin picture Johan Levin · Jan 8, 2010 · Viewed 39.2k times · Source

With ASP.NET the tag IDs are pretty volatile so to make my tests more robust I want to locate elements by their label texts. I have played some with WatiN and it does this perfectly but that project seem kind of dead nowadays so I thought I'd look into Selenium as well before I decide on a framework.

I have html that looks something like this

<label for="ctl00_content_loginForm_ctl01_username">Username</label>:
<input type="text" id="ctl00_content_loginForm_ctl01_username" />

I don't want to type:

selenium.Type("ctl00_content_loginForm_ctl01_username", "xxx");

That is too reliant on the ID. In WatiN I'd write:

browser.TextField(Find.ByLabelText("Username")).TypeText("xxx");

Is there a way to do this in Selenium?

Answer

Michiel van der Wulp picture Michiel van der Wulp · Nov 25, 2011

This works:

//input[@id=(//label[text()="Username"]/@for)]

Explanation: Since you are looking for the input:

//input[@id=("ctl00_content_loginForm_ctl01_username")]

replace the "ctl00_content_loginForm_ctl01_username" by the attribute's value of the label:

//label[text()="Username"]/@for