之前网上查资料都是 action2.click(); 经测试不行的。最后发现action2.click().perform(); 才有效。至于为什么目前还不清楚,但至少会用了。现在就把我的代码copy过来:
代码示例:
//只有对象是visible时才可以操作,所以要等待状态变为visible
WebElement mC = driver.findElement(By.xpath("//div[contains(text(),‘产品详情‘)]/../../div/img" ));
int j = 0;
while (!mC.isDisplayed() && j <5){
driver.manage().window().maximize();
Thread.sleep(1000);
j = j + 1;
System.out.println(j + ":对象不可见。");
}
System.out.println("最后对象为:"+mC.isDisplayed());
//执行这条需要导入对应的包,请根据错误提示而添加
Actions action = new Actions(driver);
//鼠标左键点击对象
action.click(mC).perform();
//鼠标右键点击对象
action.contextClick().click(driver.findElement(By.xpath("//div[contains(text(),‘产品详情‘)]/../../div/img"))).perform();
Thread.sleep(1000);
Actions action2 = new Actions(driver);
//将鼠标移到 toElement 元素中点
action2.moveToElement(mC);
//将鼠标移到元素 toElement 的 (xOffset, yOffset) 位置,相对元素的坐标
action2.moveToElement(mC,1,1);
//以鼠标当前位置或者 (0,0) 为中心开始移动到 (xOffset, yOffset) 坐标轴
action2.moveByOffset(1,1);
Thread.sleep(2000);
action2.click().perform();
其它情况参考相关文档:
1、鼠标右键点击操作:
Actions action = new Actions(driver) ;
action.contextClick(driver.findElement(By.xpath(xpath)));
2、鼠标左键双击操作:
Actions action = newActions(driver) ;
action.doubleClick(driver.findElement(By.xpath(xpath)));
3、鼠标左键按下操作:
Actions action = newActions(driver) ;
action.clickAndHold(driver.findElement(By.xpath(xpath)));
4、鼠标左键抬起操作:
Actions action = new Actions(driver);
action.release(driver.findElement(By.xpath(xpath)));
5、鼠标移动到元素上操作:
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath(xpath)));
6、组合的鼠标操作(将目标元素拖拽到指定的元素上):
Actions action = new Actions(driver);
action.dragAndDrop(driver.findElement(By.xpath(xpath)),driver.findElement(By.xpath(xpath)));
7、组合的鼠标操作(将目标元素拖拽到指定的区域里):
Actions action = new Actions(driver);
action.dragAndDrop(driver.findElement(By.xpath(xpath)),xOffset,yOffset);
8、键盘的按下操作:
Actions action = newActions(driver) ;
action.keyDown(driver.findElement(getBy()),key) ;注:key为一个Keys的实例,实例化一个F1的按键则为Keys.F1
9、按钮松开操作:
Actions action = new Actions(driver);
action.keyUp(driver.findElement(getBy()),key)
版权声明:本文为博主原创文章,未经博主允许不得转载。