How to capture tooltip in Selenium using getAttribute?


We can capture the tooltip in Selenium using the getAttribute method.

This technique can only be used for an element which has the attribute in its html code.

A tooltip text becomes visible from an element as we hover the mouse on it. To obtain the tooltip we have to pass the title as a parameter to the getAttribute method.

Let us see the html code of an element UFSC Notes having a tooltip.

Here, the tooltip text displayed from UPSC Notes is UPSC IAS Exams Notes -

TutorialsPoint which is the value set for the title attribute.

Syntax

WebElement l = driver.findElement(By.linkText("UPSC Notes"));
String a = l.getAttribute("title");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class TooltipAttribute{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      WebElement l = driver.findElement(By.linkText("UPSC Notes"));

      //get title attribute
      String a = l.getAttribute("title");
      System.out.println("Tooltip obtained from title: " + a);

      driver.quit();
   }
}

Output

Updated on: 06-Apr-2021

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements