Selenium WebDriver通过xpath定位元素并不总是有效

3

信息:

我从配置文件中获取了fieldXpath,它是"//input[@id='signin_password']"

HTML:

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

工作原理:(但并非总是如此)

进入陷阱...

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实现?

你能分享那个元素的HTML代码吗? - Amey
请指定所使用的浏览器。旧版IE在XPath方面可能会出现问题。这不会有任何影响,但您也可以尝试fieldXpath = //input[contains(@id,"signin_password")]。 - Arun Manivannan
<li><input type="password" name="signin[password]" id="signin_password" /></li> - tux23
谢谢大家,但是这是另一个问题:Selenium WebDriver中的StaleElementReferenceException。 - tux23
你对这里的答案不满意吗?请接受答案。 - Roman C
不需要! :) 我已经自己找到答案了。 - tux23
2个回答

2
我发现了一个问题...: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.*

我的代码: (在每个字段之前调用这些函数)

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

1

使用单引号'代替双引号"

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接