webDriver中如何給元素設置焦點

發表于:2013-01-15來源:Anjuke QA Team作者:小瓶蓋點擊數: 標簽:WebDriver
webDriver中如何給元素設置焦點 做自動化過程中,有時候我們需要給某個元素設置焦點,在selenium1.0中提供了給元素設置焦點的方法。但是在2.0中并沒有該辦法。如果是輸入框我們可以使用click方法

  做自動化過程中,有時候我們需要給某個元素設置焦點,在selenium1.0中提供了給元素設置焦點的方法。但是在2.0中并沒有該辦法。如果是輸入框我們可以使用click方法,來設置焦點,但是對于link連接或者button如果通過click方法勢必會跳轉到另外頁面或者提交了頁面請求。通過嘗試發現,如果在元素上進行右擊,也可以設置焦點,但是會彈出一個菜單,這個時候我們可以通過按下鍵盤的esc鍵來取消右擊彈出的菜單,這樣焦點就可以設置成功了。下面我通過鍵盤和鼠標事件組合來實現該功能。代碼如下:

  import java.awt.AWTException;

  import java.awt.Robot;

  import java.awt.event.KeyEvent;

  import org.openqa.selenium.By;

  import org.openqa.selenium.WebDriver;

  import org.openqa.selenium.WebElement;

  import org.openqa.selenium.firefox.FirefoxDriver;

  import org.openqa.selenium.firefox.FirefoxProfile;

  import org.openqa.selenium.interactions.Actions;

  import org.openqa.selenium.remote.DesiredCapabilities;

  import org.testng.annotations.AfterMethod;

  import org.testng.annotations.BeforeMethod;

  import org.testng.annotations.Test;

  public class TestActive {

  WebDriver driver = null;

  Actions action = null;

  Robot robot = null;

  @BeforeMethod

  public void setUp(){

  try {

  robot = new Robot();

  } catch (AWTException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  System.setProperty(“webdriver.firefox.bin”, “D:/Firefox/firefox.exe”);

  FirefoxProfile file = new FirefoxProfile();

  DesiredCapabilities ds = DesiredCapabilities.firefox();

  ds.setCapability(FirefoxDriver.PROFILE, file);

  driver = new FirefoxDriver(ds);

  action = new Actions(driver);

  }

  @AfterMethod

  public void tearDown(){

  }

  @Test

  public void start(){

  driver.get(“http://www.baidu.com”);

  driver.manage().window().maximize();

  //查找你需要設置焦點的元素

  WebElement button = driver.findElement(By.xpath(“//*[@id='nv']/a[5]“));

  //對該元素進行右擊操作

  action.contextClick(button).perform();

  //按ESC鍵返回,設置焦點成功

  robot.keyPress(KeyEvent.VK_ESCAPE);

  }

  }

原文轉自:http://www.baidu.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97