Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from <h3> tag in Selenium WebDriver, Java

I have html code:

<div class="description">
<h3><strong>Samsung</strong> Galaxy SII (I9100)</h3>
<div class="phone_color"> ... </div>
...
</div>

I want to get the value Samsung Galaxy SII (I9100) from /h3> tag using Selenium 2 (WebDriver)

Any one know how to do it?

like image 415
user1494328 Avatar asked Aug 10 '12 13:08

user1494328


1 Answers

This is written in C#, but it shouldn't be difficult to convert it over to Java:

/** Declare variables **/
string descriptionTextXPath = "//div[contains(@class, 'description')]/h3";

/** Find the element **/
IWebElement h3Element = driver.FindElement(By.XPath(descriptionTextXPath));

/** Grab the text **/
string descriptionText = h3Element.Text;

Depending on whether you have other div elements with the 'description' class, you may need to further fine tune your results.


Just in case:

In order to find all divs on the page that act as descriptions for further use, you can do this:

/** Declare XPath variable **/
string descriptionElementXPath = "//div[contains(@class, 'description')]";

/** Grab all description div elements **/
List<IWebElement> descriptionElements = driver.FindElements(By.XPath(descriptionElementXPath ));

You can then use a forloop to go through each element and grab the data you need.

The following is the conversion of above C# code to Java:

/** Declare variables **/

String descriptionTextXPath = "//div[contains(@class, 'description')]/h3";

/** Find the element **/

IWebElement h3Element = driver.findElement(By.xpath(descriptionTextXPath));

/** Grab the text **/

String descriptionText = h3Element.toString();

OR,

String descriptionText = h3Element.getText();
like image 187
Michael Bautista Avatar answered Sep 23 '22 18:09

Michael Bautista