使用 Selenium Webdriver 測試某個元素是否獲得焦點。


我們可以使用 Selenium webdriver 測試某個元素是否獲得焦點。藉助於 **activeElement()** 方法可以確定這一點。首先,我們需要使用任何定位器(比如 ID、類、名稱、xpath 或 css)來識別該元素。

語法

driver.switchTo().activeElement();

讓我們考慮下面的編輯框並檢查它是否獲得焦點。

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ElementFocussed{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/index.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector(".gsc-input"));
      //activeElement() to verify element focused
      if(l.equals(driver.switchTo().activeElement()))
         System.out.println("Element is focused");
      else
         System.out.println("Element is not focused");
      driver.close();
   }
}

輸出

更新於: 18-9-2020

4K+ 次瀏覽

啟動您的 職業

完成課程獲得認證

開始
廣告