views:

419

answers:

2

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?

+1  A: 

Yes, you can use XPath, CSS or DOM locators to identify your element. In this example your XPath could look like //lable[@for='ctl00_content_loginForm_ctl01_username'] to identify that particular label.

John
Except it's not the label I want to identify - it is the input box.
Johan Levin
Oh then change the XPath to look for that input - in this case://input[@id='ctl00_content_loginForm_ctl01_username']Here is the explanation for it - you are looking for all the input elements (hence //) where the attribute id equals ctl00_content_loginForm_ctl01_username
John
Yes, but my whole problem is that I don't want any of the IDs in my test code since they change as soon as I change something on the page. There was more to my question than I could fit in the headline...
Johan Levin
+1  A: 

I believe you can do this with the following:

selenium.Type(selenium.getAttribute("//label[text()='Username']@for"), "xxx");

The text()='Username' bit gets the label you want by its innerHTML, then the @for gives you back the value of its "for" attribute.

Heads up: this is not tested (apologies for that!) but I think it'll work, based on some tooling around in the IDE plugin

Paul
It looks promising. I will give it a try tomorrow.
Johan Levin
Thanks. That worked fine (except GetAttribute should be capitalized). The syntax is nowhere near as nice as WatiN's but it will get the job done.
Johan Levin