I am accessing a Quebec Laws website and I am trying to web scrape all of its law names along with their associated PDFs. When doing this, I open each and every tab of each law and then go through all those tabs to get the information I am looking for. However, after a while of going through the tabs I get the following error: "Exception in thread "main" org.openqa.selenium.NoSuchWindowException: no such window: target window already closed ". I am unsure why this is popping up. I believe it's because the number of tabs is so long as the same code I used for a smaller number of tabs worked fine. Here is my code: `
System.setProperty("webdriver.chrome.driver", "C:\\WorkSpace\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5000));
driver.manage().window().maximize();
driver.get("http://www.legisquebec.gouv.qc.ca/en/chapters?corpus=regs&selection=all");
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("tr.clickable a"), 100));
Thread.sleep(50);
List<WebElement> QuebecConsolidatedRegulations = driver.findElements(By.cssSelector("tr.clickable a"));
String parent = driver.getWindowHandle();
for (int i=0; i<QuebecConsolidatedRegulations.size(); i++){
String opentabs = Keys.chord(Keys.CONTROL, Keys.ENTER);
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", QuebecConsolidatedRegulations.get(i));
Thread.sleep(300);
wait.until(ExpectedConditions.visibilityOf(QuebecConsolidatedRegulations.get(i)));
QuebecConsolidatedRegulations.get(i).sendKeys(opentabs);
}
int i=0;
Set<String> tabs = driver.getWindowHandles();
for (String child:tabs){
// try{
if (!parent.equalsIgnoreCase(child)){
driver.close();
driver.switchTo().window(child);
String StatuteName = driver.findElement(By.xpath("//*[@id='form']/div[2]/div[1]/h3")).getText();
String pagePdfUrl = driver.findElement(By.xpath("//*[@id='renditionPdf']")).getAttribute("href");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
if (i<QuebecConsolidatedRegulations.size()){
ConsolidatedRegulationsAndPDFs.put(StatuteName, pagePdfUrl);
i+=1;
}
else{
continue;
}
}
// }
// catch(NoSuchWindowException e){
// continue;
// }
}
return ConsolidatedRegulationsAndPDFs;
}`