Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium not finding element

This is the HTML: https://www.dropbox.com/s/aiaw2u4j7dkmui2/Untitled%20picture.png

I don't understand why this code doesn't find the element on the page. The website doesn't use iframes.

@Test
public void Appointments() {
    driver.findElement(By.id("ctl00_Header1_liAppointmentDiary"));
}

this is the error message I get:

FAILED: Appointments
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"ctl00_Header1_liAppointmentDiary"}
like image 921
Hoyesic Avatar asked Jul 06 '26 14:07

Hoyesic


2 Answers

Is this a timing issue? Is the element (or the whole page) AJAX-loaded? It's possible that it's not present on the page when you're trying to look for it, WebDriver is often "too fast".

To solve it, is either implicit or explicit wait.

The Implicit Wait way. Because of the implicit wait set, this will try to wait for the element to appear on the page if it is not present right away (which is the case of asynchronous requests) until it times out and throws as usual:

// 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();
    ...
}

The Explicit Wait way. This will only wait for this one element to be present on the page when looking for it. Using the ExpectedConditions class, you can wait for different things, too - the element to be visible, clickable etc.:

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();
    ...
}
like image 51
Petr Janeček Avatar answered Jul 09 '26 06:07

Petr Janeček


You're searching for ctl00_Header1_liAppointmentDiary, but there only is Header1_liAppointmentDiary, those are not the same...

ctl00_Header1_liAppointmentDiary != Header1_liAppointmentDiary
like image 21
jlordo Avatar answered Jul 09 '26 06:07

jlordo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!