Find Broken links in a page.
package test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrokenLinks2 {
static String testPage = "http://google.com/";
static int count;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\Drive\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(5000, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
driver.get(testPage);
List<WebElement> links = driver.findElements(By.tagName("a"));// anchor link
int numOfaTags = links.size();
System.out.println("The number of anchor links " + numOfaTags);
ArrayList<String> alist = new ArrayList<>();
for (int i = 0; i < numOfaTags; i++) {
WebElement hrefLink = links.get(i);
String eachhref = hrefLink.getAttribute("href");
alist.add(eachhref);
// checkBrokenLinks(eachhref);
// }
// driver.quit();
// }
//
// public static void checkBrokenLinks(String urls) {
try {
count ++;
URL url = new URL(eachhref);
// create a connection
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
Thread.sleep(100);
httpConnection.connect();
// get response code
int responseCode = httpConnection.getResponseCode();
System.out.println("count is " + count + " " + responseCode + " " + eachhref);
if (eachhref == null || eachhref.isEmpty()) {
System.out.println("URL is either empty or not configured for anchor tag.");
continue;
}
if (!(eachhref.startsWith(testPage))) {
System.out.println("URL belongs to another domain: " + eachhref);
continue;
}
if (responseCode >= 400) {
System.out.println("This link is broken " + eachhref);
} else {
System.out.println("This link is valid " + eachhref);
}
} catch (Exception e) {
e.printStackTrace();
}
}
driver.quit();
}
}
No comments:
Post a Comment