如何在 Selenium WebDriver 中获取工具提示文本?
seleniumautomation testingtesting tools
我们可以使用 `getAttribute` 方法在 Selenium WebDriver 中获取工具提示文本。`title` 属性需要作为参数传递给此方法。
此方法仅适用于具有 `title` 属性的元素。
工具提示文本是指鼠标悬停在元素上时显示的内容。在下面的 HTML 代码中,带有工具提示的元素具有 `title` 属性,并且 `title` 的值实际上就是工具提示文本。
![]()
下图显示了"Coding Ground"菜单,其工具提示文本为"Coding Ground - 免费在线 IDE 和终端"。

语法
WebElement m = driver.findElement(By.linkText("Coding Ground"));
String s = m.getAttribute("title");
示例
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 ToolTipTxt{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//隐式等待
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL 启动
driver.get("https://www.tutorialspoint.com/index.htm");
// 识别元素
WebElement l=driver.
findElement(By.linkText("Coding Ground"));
// 获取标题属性值
String t = l.getAttribute("title");
System.out.println("Retrieved tooltip text as :" +t);
driver.quit();
}
}
输出


