5

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?

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
user1494328
  • 681
  • 3
  • 14
  • 20

4 Answers4

3

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();
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Michael Bautista
  • 1,220
  • 12
  • 19
2
WebElement divElement = driver.findelement(By.classname("description"));
String str = divElement.getText();
System.out.println(str);

This is perfect.. It helped.. Thank you :)

Tanushree
  • 41
  • 2
0
WebElement divElement = driver.findelement(By.classname("description"));
String str = divElement.getText();
enter code here

str contains the value.

HemChe
  • 2,249
  • 1
  • 21
  • 33
Nikhil M
  • 56
  • 8
0
webDriver.findElement(By.tagName("h3"));
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182