我只是尝试使用一组键盘操作以大写字母输入文本。这里使用接口(interface)“Action”的代码:
WebElement element = driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
Action act = builder.moveToElement(element)
.keyDown(element,Keys.SHIFT)
.sendKeys("vishal")
.keyUp(Keys.SHIFT)
.build();
act.perform();
以上工作正常。
但是如果我们不使用接口(interface),它就不起作用,为什么???虽然这执行得很好,但没有执行任务。我认为两者都应该有效。
WebElement element = driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
builder.moveToElement(element)
.keyDown(element,Keys.SHIFT)
.sendKeys("vishal")
.keyUp(Keys.SHIFT)
.build();
builder.perform();
最佳答案
在第二个示例中,这是因为您先调用 build(),然后调用 perform()
如果您查看这两个方法的 Actions 类实现:
/**
* Generates a composite action containing all actions so far, ready to be performed (and
* resets the internal builder state, so subsequent calls to build() will contain fresh
* sequences).
*
* @return the composite action
*/
public Action build() {
CompositeAction toReturn = action;
resetCompositeAction();
return toReturn;
}
/**
* A convenience method for performing the actions without calling build() first.
*/
public void perform() {
build().perform();
}
当您调用build()时,它实际上会重置构建器的内部状态!
之后,当您调用perform()时,它会重建一个没有定义行为的空对象引用。
要解决此问题,我建议将对 build() 的调用替换为对 perform() 的调用,如下所示。
WebElement element = driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
builder.moveToElement(element).keyDown(element, Keys.SHIFT).sendKeys("vishal").keyUp(Keys.SHIFT).perform();
我希望根据实现来完成您想要的操作。
My investigation was done against selenium v 2.53.0
关于java - webdriver 中的一系列多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37469620/