Last active
March 9, 2023 11:00
-
-
Save adojos/40a70c56f031a25920187fedd77e97bd to your computer and use it in GitHub Desktop.
Selenium: Find Broken Links using Selenium #selenium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package automationproject; | |
| import java.io.IOException; | |
| import java.net.MalformedURLException; | |
| import java.net.HttpURLConnection; | |
| import java.util.Iterator; | |
| import java.net.URL; | |
| import java.util.List; | |
| import org.openqa.selenium.*; | |
| import org.openqa.selenium.chrome.ChromeDriver; | |
| public class MyBrokenLinks { | |
| public static void main(String[] args) { | |
| System.setProperty("webdriver.ie.driver","C:\\Users\\chand\\eclipse-workspace\\first test\\chromedriver.exe"); | |
| WebDriver mydriver = new ChromeDriver(); | |
| String myhomePage = "https://www.google.co.uk"; | |
| String myurl = ""; | |
| HttpURLConnection myhuc = null; | |
| int responseCode = 200; | |
| mydriver = new ChromeDriver(); | |
| mydriver.manage().window().maximize(); | |
| mydriver.get(myhomePage); | |
| List < WebElement > mylinks = mydriver.findElements(By.tagName("a")); | |
| Iterator < WebElement > myit = mylinks.iterator(); | |
| while (myit.hasNext()) { | |
| myurl = myit.next().getAttribute("href"); | |
| System.out.println(myurl); | |
| if (myurl == null || myurl.isEmpty()) { | |
| System.out.println("Empty URL or an Unconfigured URL"); | |
| continue; | |
| } | |
| if (!myurl.startsWith(myhomePage)) { | |
| System.out.println("This URL is from another domain"); | |
| continue; | |
| } | |
| try { | |
| myhuc = (HttpURLConnection)(new URL(myurl).openConnection()); | |
| myhuc.setRequestMethod("HEAD"); | |
| myhuc.connect(); | |
| responseCode = myhuc.getResponseCode(); | |
| if (responseCode >= 400) { | |
| System.out.println(myurl + " This link is broken"); | |
| } | |
| else { | |
| System.out.println(myurl + " This link is valid"); | |
| } | |
| } catch(MalformedURLException ex) { | |
| ex.printStackTrace(); | |
| } catch(IOException ex) { | |
| ex.printStackTrace(); | |
| } | |
| } | |
| mydriver.quit(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment