Reputation: 1698
I have to access all the anchors on a specific div. Then, I have to assert if
How can this be done?
Upvotes: 0
Views: 536
Reputation: 1698
I used the following methods to verify if the links are opening a new window and are not broken. Code comments explains the code.
public boolean xAnchors()
{
String parentHandle = driver.getWindowHandle(); // get the current window handle
// System.out.println(parentHandle);
boolean isValidated = true;
try{
List<WebElement> anchors = wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.xpath("//div[@class='container-with-shadow']//a")))); // This is an array of anchor elements
try
{
for (WebElement anchor : anchors){ //Iterating with the anchor elements
String anchorURL = anchor.getAttribute("href");
anchor.click();
String newWindow ="";
for (String winHandle : driver.getWindowHandles()) {
// System.out.println(winHandle);
driver.switchTo().window(winHandle); // switch focus to the new window
newWindow = winHandle; //Saving the new window handle
}
//code to do something on new window
if(newWindow == parentHandle) //Checking if new window pop is actually displayed to the user.
{
isValidated = false;
break;
}
else
{
boolean linkWorking = verifyLinkActive(anchorURL); //Verifying if the link is Broken or not
if(linkWorking)
{
System.out.println("The anchor opens a new window and the link is not broken");
isValidated = true;
}
else
{
System.out.println("The anchor either does not open a new window or the link is broken");
isValidated = false;
}
}
driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window
}
}
catch(Exception e)
{
isValidated = false;
}
}
catch(Exception e)
{
System.out.println("No Anchors founds on this page.");
isValidated = true;
}
System.out.println(isValidated);
return isValidated;
}
public boolean verifyLinkActive(String linkUrl){
try {
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.setRequestMethod("GET");
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND){
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage()
+ " - "+ HttpURLConnection.HTTP_NOT_FOUND);
return false;
}
else
{
return true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Upvotes: 0
Reputation: 143
use findbyelements to collect list of links. Put them into a loop and select a link. then use "getWindowHandle" to switch to new window where an assertion can be implemented that "Page Doesn;t exist" or some other error message not displayed. This will ensure whether a link is broken
Upvotes: 1