元素已启用并显示。但是,尝试单击按钮元素时出现错误。
错误:java.lang.IllegalMonitorStateException
查看我的代码以获取更多详细信息。
Actions actions = new Actions(driver);
actions.moveToElement(element, element.getLocation().x, element.getLocation().y).wait(3000);
element.click();
最佳答案
IllegalMonitorStateException
按照Java Docs的说明,抛出IllegalMonitorStateException表示线程已尝试在对象的监视器上等待,或者通知其他线程在对象的监视器上等待而不拥有指定的监视器。
public class IllegalMonitorStateException
extends RuntimeException
从类java.lang.Object继承的相关方法如下:
Object.notify()
:唤醒正在该对象的监视器上等待的单个线程。Object.notifyAll()
:唤醒正在该对象的监视器上等待的所有线程。Object.wait()
:使当前线程等待,直到另一个线程为此对象调用notify()
方法或notifyAll(
)方法。Object.wait(long)
:使当前线程等待,直到另一个线程为此对象调用notify()
方法或notifyAll()
方法,或者经过了指定的时间。Object.wait(long, int)
:使当前线程等待,直到另一个线程为此对象调用notify()
方法或notifyAll()
方法,或者其他某个线程中断了当前线程,或者经过了一定的实时时间。当您使用Selenium时,这些
wait()
方法无法在此处使用,并且需要将WebDriverWait与ExpectedConditions结合使用,并且可以使用以下解决方案:WebElement element = driver.findElement(By.cssSelector("css_of_the_element"))
new Actions(driver).moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(element))).click().build().perform();
在这里您可以找到有关Difference between driver.manage.wait(long timeout) and Explicit wait的相关讨论