Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take text from an HTML element which uses a custom attribute?

I am working on Selenium framework 2.0 Web driver and I would like to get value from a span which has a attribute like data-automation-id. The HTML code is as below

<span data-automation-id="SEL_ERR">
  Error Description
</span>

Now I want to read the text with in span that has a attribute data-automation-id set to SEL_ERR.

Can some one help me in fixing the code as I have already tried the one below but in vain.

driver.findElement(By.tagName("span")).getAttribute("data-automation-id");
like image 573
Java Beginner Avatar asked Nov 08 '13 14:11

Java Beginner


1 Answers

It's simple, really. You are currently getting the very first span in the entire document.

How do you know if that is the one you want?

Meet, .findElements(). Instead of getting the very first element that meets a locator, it will give you a list of every element that meets a criteria.

You've not shared much of the HTML, so I don't know if this is a unique element or not.

However, you have two approaches to this:

1) Use .findElements to get all the span element's and then filter it down to the elements that specifically have the attribute data-automation-id with a value of SEL_ERR

or (recommended):

2) Use .findElement with a selector that specifically targets the element talked about in 1)...if Selenium cannot find it, with a much more targeted selector, then you know it doesn't exist.

driver.findElement(By.cssSelector("span[data-automation-id='SEL-ERR']"));

or:

3) A modification of 2). If Selenium cannot find it, it'll throw an exception. Exceptions are costly. You can use .findElements instead (mentioned in 1)), which will simply return an empty list if it cannot find the element you are looking for:

driver.findElements(By.cssSelector("span[data-automation-id='SEL-ERR']")).size() != 0;
like image 50
Arran Avatar answered Sep 28 '22 07:09

Arran