Webdriver selenium,java.lang.NullPointerException,while trying to locate a Webelement

我与影子孤独终老i 提交于 2019-12-02 07:11:26

It is good practice to deal with internally as well explicit wait for locating element. If there is page related activity then also need to use wait for page to load.

Please follow bellow code For internal Wait

protected WebElement waitForPresent(final String locator) {
    // timeout is your default wait timeout in long.
    return waitForPresent(locator, timeout);
}

For Explicit Wait

protected WebElement waitForPresent(final String locator, long timeout) {
    WebDriverWait wait = new WebDriverWait(driver, timeout);
    WebElement ele = null;
    try {
        ele = wait.until(ExpectedConditions
                .presenceOfElementLocated(locator));
    } catch (Exception e) {
        throw e;
    }
    return ele;
}

protected WebElement waitForNotPresent(final String locator, long timeout) {
    timeout = timeout * 1000;
    long startTime = System.currentTimeMillis();
    WebElement ele = null;
    while ((System.currentTimeMillis() - startTime) < timeout) {
        try {
            ele = findElement(locator);
            Thread.sleep(1000);
        } catch (Exception e) {
            break;
        }
    }
    return ele;
}

Just spit balling here, but in addition to the copy/paste issues stated above.. I don't see where you do a 'get' to load the gmail page for the driver instance you are creating? Something like..

driver.get("https://mail.google.com/something");

Also, it would probably be a good idea to put an explicit wait in place for the "Email" field before doing the findElement as the page may still be rendering:

Wait<WebDriver> doFluentWait = fluentWait = new FluentWait<>(driver).withTimeout(PAGE_LOAD_WAIT, TimeUnit.SECONDS)
                                    .pollingEvery(POLLING_INTERVAL, TimeUnit.SECONDS)
                                    .ignoring(NoSuchElementException.class);

and then do something like

 doFluentWait.until(WebDriverUtil.elementIsVisible(By.name("Email")));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!