How can we find broken links using selenium
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;
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 IOException {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://bstackdemo.com/");
List<WebElement> aTags = driver.findElements(By.tagName("a"));
List<String> links = aTags.stream().map(e -> e.getAttribute("href")).collect(Collectors.toList());
/*
* for(String link: links) { verifyLink(link); }
*/
links.stream().forEach(link -> {
try {
verifyLink(link);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
});
driver.quit();
}
public static void verifyLink(String link) throws IOException {
URL url = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200) {
System.out.println(url +" - "+httpURLConnection.getResponseMessage());
}else {
System.out.println(url+" - "+httpURLConnection.getResponseMessage()+" is a broken link.");
}
}
}