当我对我之前在我的代码中执行的相同WebElement执行click()时,我得到nullpointer异常

时间:2016-09-19 12:29:59

标签: java selenium nullpointerexception

我在Java和Selenium上得到了很好的帮助。当我使用相同的" Input_Search_Box" Webelement执行click方法会抛出一个nullpointer异常。我已经谷歌搜索并尝试了一些工作,如添加线程,添加显式等待但仍然没有线索,我想念。任何建议将不胜感激。

这是我的代码:

 public class Testclass {
    WebElement Input_Search_Box;
    WebDriver driver;
    @Test
    public void openBrowser() throws Exception{
        System.setProperty("webdriver.chrome.driver","E:\\Ecilpse\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://en.wikipedia.org/wiki/Main_Page");
        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        driver.manage().window().maximize();

        JavascriptExecutor jse = (JavascriptExecutor)driver;
        jse.executeScript("window.scrollBy(0,500)");    

        WebElement Click_Create_Book = driver.findElement(By.xpath(".//*[@id='coll-create_a_book']/a"));
        Click_Create_Book.click();

        WebElement Start_Book_Creator_Btn = driver.findElement(By.xpath(".//*[@id='mw-content-text']/form/div/div[1]/button"));
    Start_Book_Creator_Btn.click();

    Input_Search_Box = driver.findElement(By.xpath(".//*[@id='searchInput']"));
        Input_Search_Box.click();
        Input_Search_Box.sendKeys("Selenium",Keys.ENTER);

    for(int i =0;i<=8;i++){
            try{

                if(driver.findElement(By.xpath(".//*[@id='siteNotice']/div[2]/div[2]/div")).isDisplayed())
                    break;
            }
    catch(Exception e){
                jse.executeScript("window.scrollBy(0,2500)");

    }
    }

    for(int j=0;j<=5;j++){

    if(driver.findElement(By.id("coll-add_article")).isDisplayed()) {
    System.out.println("If Executed");
    break;

    }else
    {

    WebElement Book_Remove = driver.findElement(By.xpath(".//*[@id='coll-remove_article']"));
                Book_Remove.click();

    }
    }

    WebElement Add_This_Book = driver.findElement(By.xpath(".//*[@id='coll-add_article']"));
    Add_This_Book.click();
    Thread.sleep(3000);

    for(int k =0;k<=6;k++){
    jse.executeScript("window.scrollBy(0,-2500)");
    Thread.sleep(3000);
    }


    Thread.sleep(4000);
    System.out.println("Sctipr on hold for 4k seconds");

    //Here is the Nullpointer error occuring
    Input_Search_Box.click();
    Input_SearchBox.sendKeys("JSCRIPT",Keys.ENTER);      

    }   

    }

1 个答案:

答案 0 :(得分:0)

如果页面已更改/重新加载,则需要再次使用find。

有时在用户操作上,页面可以触发可以更改页面的调用,该页面可以更改页面状态并且当前找到的对象丢失,这可能导致过时的元素异常或null异常。