How to capture tooltip in Selenium using Actions Class?


We can capture the tooltip on an element in Selenium using the Actions class. First, we shall have to create an object of the Actions class and then apply moveToElement to it.

This method shall move the mouse to the middle of the element for which we want to capture the tooltip followed by the perform method. Finally, we can obtain the tooltip text with the help of the getText method. This technique is used when the element having a tooltip text does not have a title attribute in its html code.

Syntax

WebElement m=driver.findElement(By.linkText("Q/A"));
Actions a = new Actions(driver);
a.moveToElement(m).perform();

Let us capture the tooltip text – We ask for your age only for statistical purposes, obtained on hovering over edit box with a label as Your age −

Let us have a look at the html code of the edit box with a tooltip. This element does not have the title attribute.

Next to capture the html code of the tooltip, first click on F12 to open the Console in the Chrome browser. Then press F8 or Function + F8 to make the browser in the Paused in debugger mode.

Then inspect the tooltip text to get its html attributes.

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;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.JavascriptExecutor;
public class ToolTipActions{
   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);
      //maximize browser
      driver.manage().window().maximize();
      //URL launch
      driver.get("https://jqueryui.com/tooltip/");
      // identify frame then switch to it
      WebElement f=driver.findElement(By.className("demo-frame"));
      driver.switchTo().frame(f);
      //identify element
      WebElement m=driver.findElement(By.xpath("//input[@id='age']"));
      //scroll to element with JavaScript Executor
      JavascriptExecutor js = (JavascriptExecutor) driver;
      js.executeScript("arguments[0].scrollIntoView(true);", m);
      // object of Actions with method moveToElement
      Actions at = new Actions(driver);
      at.moveToElement(m).perform();
      //identify tooltip element
      WebElement n=driver.findElement(By.xpath("//div[@class='ui-tooltip-content']"));
      //get text of tooltip
      String s = n.getText();
      System.out.println("Tooltip is :"+s);
      driver.quit();
   }
}

Output

Updated on: 06-Apr-2021

545 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements