您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
webDriver中如何給元素設置焦點
作者:網(wǎng)絡轉載 發(fā)布時間:[ 2013/4/15 16:01:24 ] 推薦標簽:

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

  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);

  }

  }

軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd