2016-09-07 176 views
0

我是Selenium和WebDriver中的新成員。 我有這樣的HTML:Webdriver - 無法找到元素(Java)

<input id="undefined-undefined-Jobsubject-5546" type="text" value="" data-test="testing-job-subject" style="padding: 0px; position: relative; width: 100%; border: medium none; outline: medium none; background-color: transparent; color: rgb(255, 255, 255); cursor: initial; font: inherit; height: 100%; box-sizing: border-box; margin-top: 14px;"/>

,我有這樣的代碼:

driver.findElement(By.xpath("//input[@data-test='testing-job-subject']")); 

但錯誤是:

org.openqa.selenium.NoSuchElementException: Unable to locate element: //input[@data-test='testing-job-subject']

我也試過這樣:

driver.findElement(By.xpath("//*[starts-with(@id,'undefined-undefined-Jobsubject')]")); 

因爲id中的數字是生成的,所以我不能接受By.id(....),但是同樣的錯誤。 是的,我在代碼中有超時,所以元素在頁面上。

問題在哪裏?由於

回答

2

如果你正在NoSuchElementException爲您提供的異常,可能有以下幾個原因: - 當你要尋找元素

  • 可能是,它將不會出現在DOM,所以你應該執行WebDriverWait等到元素可見如下: -

    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[data-test='testing-job-subject']"))); 
    
  • 可能是此元素在任何frameiframe之內。如果是,你需要切換該frameiframe尋找元素,如下之前: -

    WebDriverWait wait = new WebDriverWait(driver, 10); 
    
    //Find frame or iframe and switch 
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name")); 
    
    //Now find the element 
    WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[data-test='testing-job-subject']"))); 
    
    //Once all your stuff done with this frame need to switch back to default 
    driver.switchTo().defaultContent(); 
    
+0

我試過了第一個原因,但仍然沒有,只是另一個錯誤: 「org.openqa.selenium.TimeoutException:預期的條件失敗:等待By.cssSelector定位的元素的可見性:input [data-test ='testing ](用500 MILLISECONDS間隔嘗試10秒)「 並且沒有框架或iframe:/ – Mephy

+0

那麼如何確保您沒有框架或iframe? –

+0

@Mephy你確定你在這裏提供了鏈接元素的正確的HTML代碼?並確保該元素在頁面上可手動顯示。 –

0

試試這個:

WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[data-test='testing-job-subject']"))); 
0

我覺得下面應該

你driver.findElement工作(By.cssSelector(」 ID * = 'Jobsubject'「));