如何使用 getAttribute 在 Selenium 中捕获工具提示?

seleniumautomation testingtesting tools

我们可以使用 getAttribute 方法在 Selenium 中捕获工具提示。

此技术仅适用于 HTML 代码中具有该属性的元素。

当我们将鼠标悬停在元素上时,工具提示文本会从元素中可见。要获取工具提示,我们必须将标题作为参数传递给 getAttribute 方法。

让我们看一下带有工具提示的 UFSC Notes 元素的 HTML 代码。

此处,UPSC Notes 显示的工具提示文本为 UPSC IAS Exams Notes -

TutorialsPoint,它是为 title 属性设置的值。

语法

WebElement l = driver.findElement(By.linkText("UPSC Notes"));
String a = l.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 TooltipAttribute{
   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("UPSC Notes"));

      //获取 title 属性
      String a = l.getAttribute("title");
      System.out.println("Tooltip obtained from title: " + a);

      driver.quit();
   }
}

输出


相关文章