find broken links on a webpage
Following code snippet can be used to details of link and their working / not working (broken) details on a page
package practice;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class VerifyLinks {
public static void main(String[] args) throws ClientProtocolException, IOException {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http://the-internet.herokuapp.com/iframe”);
List
System.out.println(“Total links are ” + links.size());
Iterator
Map
while (itr.hasNext()) {
WebElement element = itr.next();
String url = element.getAttribute(“href”);
String b = verifyLinkActive(url);
status.put(url, b);
}
for (Map.Entry
System.out.println(my.getKey() + “==>” + my.getValue());
}
}
public static String verifyLinkActive(String linkUrl) throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(linkUrl);
HttpResponse response = client.execute(getRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
return “false”;
} else {
return “true”;
}
}
}
0 comments