aleja20.06
aleja20.06

Reputation: 11

How can I get the text of an HTML element with Selenium?

I'm trying to get the text of HTML elements. I can do it in the console:

$('h2').textContent

But, when I'm going to do it in Eclipse with Selenium, I can't get to text. I'm trying with:

WebElement Text = driver.findElement(By.cssSelector("$ ('h2').textContent"));

And...

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('h2').textContent");

And it doesn’t work:

driver.find_element_by_xpath("//*[label='Titular:']/following-sibling::*[1]").text

Upvotes: 1

Views: 2065

Answers (3)

Syagin Kumar
Syagin Kumar

Reputation: 19

Please Use

String Text = driver.findElement(By.tagName("h2")).getText();

Upvotes: 1

Lora Borisova
Lora Borisova

Reputation: 21

In general, you should locate the element correctly and execute .getText() on it, as suggested in previous answers.

A possible reason for not-working may be only an incorrect element location. Please be sure to uniquely identify the element by a given static property (assure it is not dynamically constructed). If this does not work, please place closest to the element HTML hierarchy part, so that we can help you.

Upvotes: 0

Gaurav Khanna
Gaurav Khanna

Reputation: 3

If your HTML snippet looks like below, then the following code should work.

Sample HTML snippet:

<h2>Main Heading</h2>

Code

/** Find the element **/

IWebElement h2Element = driver.findElement(By.xpath(...your XPath expression...));

/** Grab the text **/

String descriptionText = h2Element.getText();

Upvotes: 0

Related Questions