In this post, we will see Selenium Broken Links | How To Find Broken Links in Selenium Webdriver Java
Broken Links
HTTP Response
/ Status Code
200:
Valid Link
400: Bad Request (Bad URL)
404: Web Page Not Found
405: Server knows the request method,
target resource doesn’t support this method
503: Server is overloaded and can not
process request
Broken if
response code>=400
Anchor
tag
<a
href=”www.comrevo.com”>Click here</a>
Program Code (BrokenLinks):
package main;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrokenLinks {
public static void main(String[] args) throws MalformedURLException, IOException {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://pict.edu/extracurricular/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
List<WebElement> links=driver.findElements(By.xpath("//a[contains(@href,'.')]"));
for(WebElement link : links)
{
String url=link.getAttribute("href");
HttpURLConnection con=(HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.connect();
int respcode=con.getResponseCode();
if(respcode>=400)
{
System.out.println("Link Text:"+link.getText()+" Response Code:"+respcode);
}
}
driver.quit();
}
}
Watch Following Video:
Watch on YouTube: https://www.youtube.com/watch?v=o8lIF4HVXRs
No comments:
Post a Comment