2013-01-22 29 views
1

我想提出一個if條件,當存在id="prog_bg"class="progress_box_bg"時,執行剩餘的代碼。 DOM如下,如果條件,在id =「prog_bg」存在的情況下,執行剩餘的代碼

<div id="wizard"> 
<div class="quote_header"> 
<div class="items"> 
     <div id="top-line" style="display: block;"> 
      <div class="back_box"> 
      <div class="progress_box"> 
       <div id="prog_bg" class="progress_box_bg" style="width: 75px;"></div> 
      </div> 
      </div> 
     <div id="service-div" class="page" style="padding-top:45px; >"> 
     <div id="propertytype-div" class="page"> 

我試了很多選擇,但它不會工作。夥計讓我知道它是怎麼做到的?

  1. if (var.equals(driver.findElement(By.tagName("body")).getText().contains("prog_bg")))
  2. try { if (selenium.getHtmlSource().matches("^[\\s\\S]*prog_bg[\\s\\S]*$")) break; } catch (Exception e) {};
  3. if(driver.getPageSource().matches("^[\\s\\S]*prog_bg[\\s\\S]*$"))
  4. if(driver.findElement(By.id("prog_bg")).isDisplayed())
  5. if (driver.findElement(By.className("progress_box_bg")).isDisplayed())

感謝, 薩欽

+0

的可能的複製[檢查元件最好的方式是不與Java本webdriver的硒(http://stackoverflow.com/questions/12270092/best-way-to-check-that-element-is-not-本-的webdriver - 硒與 - 爪哇) –

回答

0

你也可以嘗試這樣的事情。

// Find element by id 
boolean isElementPresent = driver.findElement(By.id("prog_id")); 
// Find element by class 
boolean isElementPresent = driver.findElement(By.className("progress_box_bg")); 
//This writes out an errormessage if isElementPresent equals false, good for reports! 
Assert.assertTrue("Could not find the element", isElementPresent); 
0

你能嘗試這樣的事情?你可以用if替換Assert()

boolean ispresent= driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*prog_bg:[\\s\\S]*$");//TODO: Make this dynamic 
Assert.assertEquals(true, ispresent); 

boolean ispresent= driver.findElement(By.id("prog_id")) 
Assert.assertEquals(true, ispresent); 
0

數字4和5是在正確的軌道上。但是,你不應該叫isDisplayed(),如果你只是要檢查在DOM其存在。 isDisplayed()檢查在DOM 的元件存在,然後檢查是否該元素是用戶可見。

相反,你應該設法找到該元素本身:

if(driver.findElement(By.id("prog_bg")) || driver.findElement(By.className("progress_box_bg")) { 
/*Execute code here*/ 
} 

而且,請注意,元素屬性不會出現在網頁的正文文本,將只會出現在DOM。任何試圖找到這些元素就像你在數字1,2做的,3是完全徒勞的。

相關問題