In this tutorial, we will learn how to find broken links using Selenium. Broken links mean after clicking on this given links or URL it gives some error or not reachable. So you always make sure that there are no broken links on site because the user should not land on an error page.
1. Find all links by below code:
Steps to find broken links and handle it:-
1. Find all links of the web page.
2. Iterate each link and check if they are broken. For this Send HTTP request for the link and read response code.
List <WebElement> links = driver.findElements(By.tagName(“a”));
2. Iterate each links and check if they are broken:
For (int i =0; i<links.size; i++)
{
WebElement ele= links.get(i);
// By using href we can get url of the links
String url = ele.getAttribute(“href”);
//create object of URL class and pass url in this.
URL link = new URL(url);
//Using HttpURLConnection class create a connection
HttpURLConnection httpcon = (HttpURLConnection)link.openConnection();
httpcon.connect();
//Now using getResponseCode() to get the response code
If(httpcon.getResponseCode()==200){
System.out.println(“URL is valid link”);
}
elseif((httpcon.getResponseCode()==404){
elseif((httpcon.getResponseCode()==404){
System.out.println(“URL is broken”);
}
}
No comments:
Post a Comment