2

Can anyone help me to read a label text from selenium webdriver

The for attribute value and label text are entirely different

1
  • Please provide the HTML code so that it is easier to answer your question Commented Oct 11, 2012 at 4:09

2 Answers 2

3

Assuming the label looks in HTML something like this:

<span id="spannyspan" title="the Title of SPAN">The Text</span>

then the WebElement will be best approached like this:

WebDriver driver = new FirefoxDriver();
WebElement theSpan = driver.findElement(By.id("spannyspan"));
String title = theSpan.getAttribute("title");
String label = theSpan.getText();
System.out.println(title); // will return "the Title of SPAN"
System.out.println(label); // will return "The Text"
// both without apostrophes ofcourse

If this does not help please provide sample HTML of label which you are trying to fetch

Sign up to request clarification or add additional context in comments.

6 Comments

As I don't know- is it the best way to make a WebElement for non functional HTML Elements as a label?
In case you need get text from span, then yes. Imagine that the span will hold the Order ID which can be later on verified against database...
I just thought there could be a something like a passive WebElement with reduced instructionset
If there is, I am not aware of it
@PavelJanicek: Good example with providing HTML code by your own. According to you it would work fine, I think. But, It was better if the poster could provide the snippet of HTML code.
|
1

Suppose there is a label contain text "hello":

    <label>hello</label>

then what you have to do is: # first find this element using xpath or css locator and store that into WebElement object:

    WebElement label = driver.findElement(By.xpath("//label[contains(text(),'hello')]");

# After that using getText() method you can get the text of the label element.getText() method return value in string so,store the value in the string variable

String lbltext =  label.getText();

# After that if you want to print the value then

    System.out.println("text = "+lbltext);

1 Comment

Please consider reformatting your answer. It's quite hard to read with these monster bold texts and unformatted code snippets. Please read How do I write a good answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.