无论我使用什么搜索类型,我总是收到“找不到这样的元素”错误。为什么会出现这种情况?
public void CorrectPIN() throws InterruptedException{
driver.findElement(By.id("identifier")).sendKeys("abhisingh1313@mailinator.com");
driver.findElement(By.id("button")).click();
Thread.sleep(5000);
do {
Thread.sleep(100);
} while (driver.findElement(By.id("pin")).isDisplayed());
}
......................
无论我使用什么搜索机制,我都无法在 driver.findElement(By.id("pin")).isDisplayed())
上找到元素。我什至尝试过xpath。
基本上我希望网络驱动程序等到屏幕上出现一个元素并且它出现了,但即使这样我也不知道为什么它会给出错误无法定位元素错误。
最佳答案
如果我正确理解了您的问题,在检查while()
内的条件时执行了所有步骤之后循环即
driver.findElement(By.id("pin")).isDisplayed();
您正在看到 NoSuchElementException
。
Java 文档明确提到 NoSuchElementException
由 WebDriver.findElement(By by)
抛出 或 WebElement.findElement(By by)
符合您的情况。
原因
查看 NoSuchElementException
的理由有很多。 。其中一些如下:
-
Locator Strategy
您已经使用过,即id
可能无法识别确切的元素。 - 该元素可能不在
Viewport
范围内. - 当您的脚本搜索该元素时,该元素可能尚未在
HTML DOM
中呈现。
解决方案
针对上述原因的解决方案是:
- 采用
Locator Strategy
这将唯一地标识预期的元素,最好是Css Selector
。您可以在Official locator strategies for the webdriver
找到详细讨论 使用
JavascriptExecutor
将元素置于Viewport
内与以下代码行。您可以在Scrolling to top of the page in Python using Selenium
找到详细讨论element = driver.find_element_by_xpath("element_xpath") self.driver.execute_script("return arguments[0].scrollIntoView(true);", element)
使用
WebDriverWait
以及适当的ExpectedCondition
等待WebElement
具有互动性。
更新
您正在看到NoSuchElementException
在下面一行:
while (driver.findElement(By.id("pin")).isDisplayed());
从您的代码块来看,您为什么要检查 driver.findElement(By.id("pin")).isDisplayed()
尚无定论。 在 while loop
。一旦你这样做driver.findElement(By.id("button")).click();
您将被重定向到带有新 HTML DOM
的新页面。 。因此,如果您想要的话,请在新页面上 driver.findElement(By.id("pin")).isDisplayed()
要想成功,你必须诱导WebDriverWait
对于WebElement
根据我的答案的解决方案#3显示。
关于java - 找不到此类元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48403496/