1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; 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 BrokenLinks { public static void main(String[] args) throws InterruptedException, IOException { // //Maximize the browser System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); //Implicit wait for 10 seconds driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://www.facebook.com/"); //Wait for 5 seconds Thread.sleep(5000); //Used tagName method to collect the list of items with tagName "a" //findElements - to find all the elements with in the current page. It returns a list of all webelements or an empty list if nothing matches List<WebElement> links = driver.findElements(By.tagName("a")); links.addAll(driver.findElements(By.tagName("img"))); //To print the total number of links System.out.println("Total links are "+links.size()); List<WebElement>activelink=new ArrayList<WebElement>(); //used for loop to ; for(int i=0; i<links.size(); i++) { if(links.get(i).getAttribute("href")!=null) { activelink.add(links.get(i)); }} System.out.println("Active links are "+activelink.size()); System.out.println("Broken links are "+(links.size()-activelink.size())); for(int j=0;j<activelink.size();j++) { HttpURLConnection Conn =(HttpURLConnection)new URL(activelink.get(j).getAttribute("href")). openConnection(); Conn.connect(); String response=Conn.getResponseMessage();//ok Conn.disconnect(); System.out.println(activelink.get(j).getAttribute("href")+"--->"+response); } driver.quit(); } } |