Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium locator for <label for="x">

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?

like image 703
Johan Levin Avatar asked Jan 08 '10 21:01

Johan Levin


People also ask

How do I find the XPath of a label?

You have to click the labels. Try .//div[@class='question-group']/label[text()='Mrs'] as xpath expression. I created a little test with the code fragement you provided above and the xpath expression is working and selects the appropriate label.

How do you find labels in Selenium?

For getting the label text we use getText method. This method returns a string value. String labelText = driver. findElement(By.id("usernamelbl")).

What are the 8 locators in Selenium?

Selenium supports 8 different types of locators namely id, name, className, tagName, linkText, partialLinkText, CSS selector and xpath.

How do I find the XPath of a tag name?

Xpath =//tagname[@Attribute='value'] Wherein: //: Used to select the current node. tagname: Name of the tag of a particular node. @: Used to select the select attribute.


2 Answers

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
like image 174
Michiel van der Wulp Avatar answered Oct 16 '22 21:10

Michiel van der Wulp


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

like image 37
Paul Degnan Avatar answered Oct 16 '22 20:10

Paul Degnan