硒没有找到元素

Hoy*_*sic 2 java eclipse selenium webdriver selenium-webdriver

这是HTML:https: //www.dropbox.com/s/aiaw2u4j7dkmui2/Untitled%20picture.png

我不明白为什么这段代码在页面上找不到元素.该网站不使用iframe.

@Test
public void Appointments() {
    driver.findElement(By.id("ctl00_Header1_liAppointmentDiary"));
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息:

FAILED: Appointments
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"ctl00_Header1_liAppointmentDiary"}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ček 9

这是时间问题吗?AJAX加载的元素(或整个页面)是?当你试图寻找它时,页面上可能没有它,WebDriver通常"太快"了.

要解决它,要么是隐式等待,要么是显式等待.

隐等待方式.由于隐式等待集,如果它不立即出现(这是异步请求的情况),它将尝试等待元素出现在页面上,直到它超时并像往常一样抛出:

// Sooner, usually right after your driver instance is created.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Your method, unchanged.
@Test
public void Appointments() {
    ...
    driver.findElement(By.id("ctl00_Header1_liAppointmentDiary")).doSomethingWithIt();
    ...
}
Run Code Online (Sandbox Code Playgroud)

明确的等待方式.这只会在查找时等待页面上出现这一个元素.使用ExpectedConditions该类,您也可以等待不同的东西 - 要显示的元素,可点击的等等:

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

@Test
public void Appointments() {
    ...
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(presenceOfElementLocated(By.id("ctl00_Header1_liAppointmentDiary")))
        .doSomethingwithIt();
    ...
}
Run Code Online (Sandbox Code Playgroud)