在webdriver的使用过程中,应该会用到使用工具来模拟用的鼠标、键盘的一些输入操作,比如说: 1、鼠标的左键点击、双击、拖拽、右键点击等; 2、键盘的回车、回退、空格、ctrl、alt、shift等;
模拟键盘的操作
Action action = new Action(driver); // 获取动作对象
action.keyDown(Keys.CONTROL); // 按下ctrl
action.keyUp(Keys.CONTROL); // 抬起ctrl
action.keyDown(Keys.SHIFT);
action.keyUp(Keys.SHIFT);
action.keyDown(Keys.ALT);
action.keyUp(Keys.ALT);
action.sendKeys(Keys.TAB).perform(); // 点击TAB按钮,按下和抬起的动作是连续的
actions.sendKeys(Keys.ENTER).perform();
有时候登陆页面在输入完用户名后可以按Tab键直接输入密码,然后Enter键登陆。这样可以免去元素的查找:
Action action = new Action(driver);
driver.findElement(By.name("uname")).sendKeys("qingdao01");
actions.sendKeys(Keys.TAB).perform();
actions.sendKeys("a123456").perform();;
actions.sendKeys(Keys.ENTER).perform();
模拟鼠标右键
Action action = new Action(driver);
action.contextClick(driver.findElement(By.id("uname"))).perfrom();
在指定元素进行鼠标悬浮
Action action = new Action(driver);
WebElement link1 = driver.findElement(By.id("link1"));
action.moveToElement(link1).perform();
鼠标单击左键和释放
Action action = new Action(driver);
WebElement link1 = driver.findElement(By.id("link1"));
action.clickAndHold(link1).perform(); // 在指定控件单击左键不释放
Thread.sleep(3000);
action.release(link1).perform(); // 释放鼠标左键
// 注意:clickAndHold和release两个方法连起来使用会被认为执行了一次click事件
拖拽页面
Action action = new Action(driver);
WebElement div= driver.findElement(By.xpath("//div"));
action.dragAndDropBy(div, 0, 50).biuld().perform();