执行滚动到selenium中的视图脚本时出现空指针异常

时间:2018-06-07 04:57:43

标签: javascript java selenium selenium-webdriver webdriver

Scroll View

ham.click();
Thread.sleep(1000);
//js.executeScript("window.scrollBy(0,500)");
WebElement we4 = driver.findElement(By.xpath(property.getProperty("Intouch")));
je.executeScript("arguments[0].scrollIntoView(true);", we4);
we4.click();
Thread.sleep(2000);

在上面的代码中,我想滚动汉堡包菜单栏,但是当我执行上面的代码行时,我发现了空指针异常。

1 个答案:

答案 0 :(得分:0)

替换您的发现

WebElement we4 = driver.findElement(By.xpath(property.getProperty("Intouch")));

使用

private WebDriverWait wait_element;

wait_element = new WebDriverWait(driver, 40);

WebElement we4 = wait_element.until(ExpectedConditions.presenceOfElementLocated(By.xpath(property.getProperty("Intouch"))));

第二,Thread.sleep();是一个坏习惯。从项目到项目,我随身携带这些帮助方法。欢迎您使用它们。

public void waitForBrowserReadystateComplete(WebDriver webDriver) {
    for (int a=0; a<20; a++) {
        JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
        if (javascriptExecutor.executeScript("return document.readyState")
                .toString().equals("complete")) {
            break;
        }
        sleepResponsibly(500);
    }
}

public void sleepResponsibly(int timeMillisecond){
    try{
        Thread.sleep(timeMillisecond);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt(); 
        throw new RuntimeException(ex);
    }
}

/**
 * 
 * @param webDriver
 * @param elementToScrollIntoView
 * @param blockOption - If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor.
 *                      If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor
 */
public void explicitScrollIntoView(WebDriver webDriver, WebElement elementToScrollIntoView, boolean blockOption) {
    final String scriptStr = "arguments[0].scrollIntoView(" + blockOption + ");";
    ((JavascriptExecutor) webDriver).executeScript(scriptStr, elementToScrollIntoView);

    sleepResponsibly(500);

}