我在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);
}
}
解决方法:
如果页面已更改/重新加载,则需要再次使用find.
有时,在用户操作时,页面可以触发可以更改页面的调用,从而可以更改页面的状态,并且当前找到的对象丢失,这可能导致陈旧元素异常或null异常.