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

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

  //查找你需要設(shè)置焦點(diǎn)的元素

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

  //對(duì)該元素進(jìn)行右擊操作

  action.contextClick(button).perform();

  //按ESC鍵返回,設(shè)置焦點(diǎn)成功

  robot.keyPress(KeyEvent.VK_ESCAPE);

  }

  }

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