如何使用 getAttribute() 在 Selenium 中捕獲工具提示?


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

此方法只能用於 HTML 程式碼中存在該屬性的元素。

當我們懸停在元素上時,工具提示文字從元素中顯示出來。要獲取工具提示,我們必須將標題作為引數傳遞給 getAttribute 方法。

讓我們看看一個帶有工具提示的元素 UFSC Notes 的 HTML 程式碼。

在此,從 UPSC Notes 中顯示的工具提示文字是 UPSC IAS Exams Notes -

TutorialsPoint 是為標題屬性設定的值。

語法

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();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://tutorialspoint.tw/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();
   }
}

輸出

更新於: 06-4 月-2021

509 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.