>我只是尝试使用一组键盘操作以大写字母输入文本。此处使用界面"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();
以上工作正常。
但是如果我们不使用接口,它就不起作用,为什么???虽然这执行正常,但没有执行任务。我认为两者都应该有效。
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() 时,它会重建一个没有定义行为的空对象引用。
为了纠正这个问题,我建议将你的调用替换为对 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();
我希望它能根据实现做你想做的事。
我的调查是针对硒 v 2.53.0 进行的
Actions#build()
方法在返回操作之前重置自身的状态,
请参阅此处的实现:http://grepcode.com/file/repo1.maven.org/maven2/org.seleniumhq.selenium/selenium-api/2.18.0/org/openqa/selenium/interactions/Actions.java#Actions.build%28%29
338
339 public Action More ...build() {
340 CompositeAction toReturn = action;
341 resetCompositeAction();
342 return toReturn;
343 }
注意resetCompositeAction();
调用 - 它会重置构建器。
如果执行此操作:
builder............
........ ().build();
builder.perform();
然后build()
返回操作并重置builder
对象的状态。
然后如果你打电话给builder.perform()
,它什么都不做。
builder.moveToElement(element)
.keyDown(element,Keys.SHIFT)
.sendKeys("vishal")
.keyUp(Keys.SHIFT)
.build().perform();