2013-07-25 313 views
2

這是HTML: https://www.dropbox.com/s/aiaw2u4j7dkmui2/Untitled%20picture.png硒找不到元素

我不明白爲什麼這個代碼沒有找到頁面上的元素。該網站不使用iframe。

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

這是錯誤消息我得到:

FAILED: Appointments 
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"ctl00_Header1_liAppointmentDiary"} 
+0

截圖不顯示ID爲'ctl00_Header1_liAppointmentDiary'任何元素,不是嗎?有'Header1_liAppointmentDiary'但是... – mthmulders

+0

您的圖像上的id是Header1_liAppointmentDiary **不** ** ctl00_Header1_liAppointmentDiary – VolkerK

+0

元素AJAX加載?你有沒有嘗試過等待它[隱式或顯式](http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#explicit-and-implicit-waits)? –

回答

2

您正在尋找ctl00_Header1_liAppointmentDiary,但僅是Header1_liAppointmentDiary,那些是不一樣的......

ctl00_Header1_liAppointmentDiary != Header1_liAppointmentDiary 
2

id="ctl00_Header1_liAppointmentDiary"您的html中沒有元素

driver.findElement(By.id("ctl00_Header1_liAppointmentDiary")); 

應該

driver.findElement(By.id("Header1_liAppointmentDiary")); 
+0

我也試過,但我得到相同的錯誤信息。我嘗試過使用xpath的findElement,但是我得到了同樣的錯誤 – Hoyesic

-1

看着代碼,我認爲你試圖點擊的鏈接是在一個下拉菜單下,或者你需要將鼠標放在某個東西上才能看到此鏈接。如果是這樣,那麼您將使該元素可見以執行該操作。

+3

如果它只是不可見,那麼元素仍然會被找到。它不會拋出'NoSuchElementException'。當你嘗試與元素交互時,它會拋出'ElementNotVisibleException'。 –

8

這是計時問題嗎?是元素(或整個頁面)AJAX加載?當您嘗試查找時,它可能不在網頁上,WebDriver通常「太快」。

要解決它,要麼是implicit or explicit wait

隱式等待的方式。由於隱含的等待設置,如果它不立即出現(這是異步請求的情況),它將嘗試等待該頁面出現在頁面上,直到它像往常一樣超時並拋出:

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

明確等待的方式。這隻會等待這一個元素出現在頁面上時,尋找它。使用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(); 
    ... 
}