在做用selenium做web自动化时,鼠标点击事件是再所难免的,所以给大家分享一下常用鼠标点击的代码
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Action {
//处理鼠标键盘操作的。
public static void main(String[] args) throws InterruptedException {
WebDriver dr = new FirefoxDriver();
dr.get("");
Thread.sleep(2000);
//1、鼠标左键点击:
Actions action = new Actions(dr);
action.click(dr.findElement(By.xpath("xpath")));//等价于 driver.findElement(By.xpath(xpath)).click();
//2、鼠标左键双击:
action.doubleClick(dr.findElement(By.xpath("xpath")));
//3、鼠标左键按下操作:
action.clickAndHold(dr.findElement(By.xpath("xpath")));
//4、鼠标左键移动到元素操作:
action.moveToElement(dr.findElement(By.xpath("xpath")));
//5、鼠标右键点击操作:
action.contextClick(dr.findElement(By.xpath("xpath")));
//6、组合的鼠标操作(将目标元素拖拽到指定的元素上):
action.dragAndDrop(dr.findElement(By.xpath("xpath")),dr.findElement(By.xpath("xpath")));
//7、组合的鼠标操作(将目标元素拖拽到指定的位置上):
action.dragAndDropBy(dr.findElement(By.xpath("xpath")),0,100); //其中 0为xOffset 为横坐标,100为yOffset 为纵坐标。
//8.拖拽选择操作,鼠标按住不放,进行拖拽选择,然后释放鼠标,需要三个动作
action.clickAndHold(dr.findElement(By.id("1"))).moveToElement(dr.findElement(By.id("3"))).perform();
action.release();
//键盘的模拟操作,包括普通按键,比如enter、backspace、tab等,还包括四个修饰键(Modifier Keys),分别是Caps Lock,Control,Option,Command。
//普通按键使用时,直接使用sendkeys(theKeys)就可以,如按下enter键:
action.sendKeys(Keys.ENTER).perform();
//使用快捷键alt+f4关闭窗口(但是该方法不稳定,时行时不行,不行居多)
action.keyDown(Keys.ALT).keyDown(Keys.F4).keyUp(Keys.ALT).perform();
//使用ctrl+a全选
action.sendKeys(Keys.CONTROL+"a").perform();
dr.quit();
}
}