2012-10-26 42 views
2

信息:硒的webdriver By.xpath不工作的所有時間

我得到fieldXpath從一個配置文件,它是"//input[@id='signin_password']"

HTML:

<li><input type="password" name="signin[password]" id="signin_password" /></li> 

作品(但不總是)

獲取在catch ...

public void doAction(WebDriver driver) throws TestException { 
     try { 
      WebElement el = driver.findElement(By.xpath(fieldXpath)); 
      el.clear(); 
      el.sendKeys(fieldValue); 
     } catch (Exception e) { 
      throw new TestException(this.getClass().getSimpleName() + ": problem while doing action : " + toString()); 
     } 
    } 

難道一個解決方案,讓使用XPath此代碼的工作?

+0

ü可以分享該元素的HTML代碼? – Amey

+0

也可以指定正在使用的瀏覽器。老版本的IE瀏覽器在使用XPath時出現問題。沒有區別,但你也可以嘗試fieldXpath = //輸入[包含(@id,「signin_password」)] –

+0

回答

1

使用單個'而不是"。所以

String fieldXpath = "//input[@id='signin_password']"; 
+0

我已經測試過這個......但是tks – tudorluchy

1

我發現這個問題...:硒的webdriver StaleElementReferenceException

*This may be caused because the page isn't loaded completely when the code starts or changes when the code is executed. You can either try to wait a little longer for the element or catch the StaleReferenceException and try again finding the div and the span.* 

我的代碼(每個字段之前調用這些函數)

/** 
* Handle StaleElementReferenceException 
* @param elementXpath 
* @param timeToWaitInSec 
*/ 
public void staleElementHandleByXpath(String elementXpath, int timeToWaitInSec) { 
    int count = 0; 
    while (count < 10) { 
     try { 
      WebElement slipperyElement = driver.findElement(By.xpath(elementXpath)); 
      if (slipperyElement.isDisplayed()) { 
       slipperyElement.click(); // may throw StaleElementReferenceException 
      } 
      count = count + 10; 
     } catch (StaleElementReferenceException e) { 
      count = count + 1; // try again 
     } catch (ElementNotVisibleException e) { 
      count = count + 10; // get out 
     } catch (Exception e) { 
      count = count + 10; // get out 
     } finally { 
      // wait X sec before doing the action 
      driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS); 
     } 
    } 
} 

/** 
* Wait till the document is really ready 
* @param js 
* @param timeToWaitInSec 
*/ 
public void waiTillDocumentReadyStateComplete(JavascriptExecutor js, int timeToWaitInSec) { 
    Boolean ready = false; 
    int count = 0; 
    while (!ready && count < 10) { 
     ready = (Boolean) js.executeScript("return document.readyState == 'complete';"); 
     // wait X sec before doing the action 
     driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS); 
     count = count + 1; 
    } 
}