tux23
tux23

Reputation: 225

Selenium WebDriver By.xpath doesn't work all the time

Info :

I get fieldXpath from a config file, and it is "//input[@id='signin_password']"

HTML:

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

WORKS : (but not always)

Gets in the 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());
         }
    }

Is there a solution that makes this code work with XPath?

Upvotes: 2

Views: 4021

Answers (2)

tux23
tux23

Reputation: 225

I found the problem... : selenium 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.*

My code : (call these functions before each field)

/**
 * 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;
    }
}

Upvotes: 2

Roman C
Roman C

Reputation: 1

Use single ' quotes instead of ". So

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

Upvotes: 1

Related Questions