You can check also: Selenium locator contains text and
firefox 52 with gecko driver 52

In most cases text extraction with selenium can be done simply by:


But in some cases this will return nothing - nested tags, wrong tags etc.
If you want to extract text in those cases you can try by this examples- java code:

Selenium extract text 4 ways

I known 4 ways to get text from selenium element. Below I'm lising all of them:

  • el.getText() - usually I'm using this one and it's working for most cases
  • el.text - is quite similar to previous and it's working the same way
  • el.getAttribute("textContent") - this one extract the text event when the previous two are not working
  • el.getAttribute("innerHTML") - this extracts the inner html which sometimes can contain html which is the only difference to the previous one.
WebElement el = driver.findElements(By.cssSelector("div.myclass"));
String title1 = el.getText()
String title2 = el.text
String title3 = el.getAttribute("textContent")
String title4 = el.getAttribute("innerHTML");

Selenium locate single tag and class by css

Extracting single element div with class - myclass

WebElement el = driver.findElements(By.cssSelector("div.myclass"));
String text = el.getAttribute("textContent")

Selenium locate all tags by css

Extracting all elements of tag div with class - myclass

List<WebElement> el = driver.findElements(By.cssSelector("div.myclass"));
for (WebElement e : el4) {
	def title = e.getText()

Selenium locate nested elements by xpath

Searching for nested tags span with class - yourclass in div with class - myclass

WebElement el = driver.findElement(By.xpath("//div[@class='myclass']//span[@class='yourclass']"));
String text = el.getText()

Selenium locate nested elements by cssSelector

Searching for nested tags span with class - yourclass in div with class - myclass by css locator. it's easier to read than previous one but it's limited to classes only

WebElement el = driver.findElement(By.cssSelector(".myclass .yourclass"));
String text = el.getAttribute("innerHTML");

Selenium locate nested elements by nested findElement

You can find nested tags by chaining findElement methods as bellow. Personally I find this method better because of it's readability and way to find if there is a problem:

WebElement el = driver.findElement(By.cssSelector("div.myclass"));
WebElement ee = el.findElement(By.cssSelector("span.yourclass"))
String text = ee.getAttribute("textContent")