Not catching NoSuchElementException

Deane Kane :

I am scraping fixtures of one website and then using another website to check each team's form. The issue I am having is that not all teams exist on the form website and I am getting a NoSuchElementException for the teams whose xPath clearing doesn't exist on the URL not found page. I am trying to catch the exception but the program still breaks.

I have added a try catch but it doesn't solve my problem, the program breaks as soon as it arrives as a non-found team.

 for(int i = 0; i < fixtures.getAwayTeams().size(); i++)
 {
     driver.navigate().to(FORMURL.concat( (fixtures.getAwayTeams().get(i)).replace( ' ', '+' )));          
     for (int j = 1; j < 11; j++) {
        String xPath = FORMXPATHONE.concat( String.valueOf( j ) ).concat(FORMXPATHTWO);
        try {
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xPath)));
            forms = driver.findElementsByXPath( xPath );
            } catch(NoSuchElementException | StaleElementReferenceException e) {
            awayTeamForm.add("No Form for Team");
            }
        for (WebElement languageElement : forms) {
            ArrayList <String> wld = new ArrayList<String>();
            wld.add( languageElement.getText() );
            String listedForm = String.join(",", wld );
            awayTeamForm.add(listedForm);
        }
    }
    }
 }  

Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: //*[@id="results"]/table/tbody/tr[1]/td[6]

Sameer Arora :

You can check that the element is present on the page or not by first fetching the element list and then checking the size of that list, if its greater than 0 then the element is present else the element is not present on the page. By this you don't need to catch the exception as well.

You can do it like:

List<WebElement> elementList = driver.findElements(By.xpath("xPath"));
if(elementList.size()>0){
    // Element is present
}
else{
    // Element is not present
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=162157&siteId=1