我正在使用Selenium WebDriver自动化一些东西。它需要填写一个表单,该表单涉及从select2下拉列表中选择一个值。这是我正在使用的代码片段-
final By SELECT_DIV = By.id("s2");
click(SELECT_DIV);
final By INPUT = By.cssSelector(".select2-drop-active .select2-input");
waitForVisibilityOfElement(INPUT);
enterCharSequence(INPUT, "someData");
waitForJSandJQueryToLoad(30);//30 seconds
final By LIST_ITEM = By.cssSelector(".select2-drop-active ul.select2-results li.select2-result-selectable");
click(LIST_ITEM);仅供参考,其中一些元素没有唯一的I,因此我使用css选择器来定位它们。
这段代码可以工作,但有时会抛出StaleElementReferenceException。这是错误:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.htmlSelenium版本: 2.53
所以,我想知道是否有任何方法可以避免这种情况。我读了一些关于它的帖子,但它们没有太大帮助。
如果你需要更多信息,请告诉我。任何帮助都将不胜感激。
发布于 2021-04-18 14:47:33
'StaleElementReferenceException‘表示元素已更改。它在另一个div中,另一个跨度或其属性已更改。Selenium可能会找到它,但在您尝试单击它的那一秒,它就改变了。
您需要再次搜索相同的元素,并等待它变为clickAble或可见。例如:
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement button =
wait.until(ExpectedConditions.
elementToBeClickable(By.id("btnLogin")));https://stackoverflow.com/questions/67141965
复制相似问题