package linkprograms;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BrokenLinksTest {
static WebDriver driver = null;
static WebDriverWait wait = null;
public static void main(String[] args) throws InterruptedException, IOException {
// 1 set the chromdriver.exe file path System.setproperty(p1,p2)
System.setProperty("webdriver.gecko.driver",
"D:\\webdriverjars\\executables\\gecko30\\geckodriver-v0.30.0-win64\\geckodriver.exe");
// Create Object for FirefoxOptions class
FirefoxOptions opt = new FirefoxOptions();
opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface variablename=new classname();
WebDriver driver = new FirefoxDriver(opt);
// maximize the window
driver.manage().window().maximize();
// add implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// create WebDriverWaitobject
wait = new WebDriverWait(driver, Duration.ofMillis(30000));
// open the rediff.com
driver.get("https://makemysushi.com/404");
// fetch all the links into List using findelements locator -tagName -a
List<WebElement> linksList = driver.findElements(By.tagName("a"));
// this is final list after removing some other links
List<String> ls = new ArrayList();
// iterating the collection to add each link to the new collection that is ls
for (WebElement e : linksList) {
String url = e.getAttribute("href");
// adding each link url to the list collection
ls.add(url);
}
// removing unwanted urls from the collection using removeAll()
ls.removeAll(Arrays.asList(null, "mailto:info@makemysushi.com"));
// validate each link by validateLinks()
for(String l:ls) {
verifyLinks(l);
}
Thread.sleep(2000);
//close the browser
driver.quit();
}
private static void verifyLinks(String url) throws IOException {
// step1. Create object for URL class
URL ul = new URL(url);
// step2:
HttpURLConnection hc = (HttpURLConnection) ul.openConnection();
// step3 connect to the url
hc.connect();
// step4 - fetch the responseStatusCode & respmessage
int respCode = hc.getResponseCode();
// fetch respMessage
String respMsg = hc.getResponseMessage();
if (respCode == 200) {
System.out.println(url+ " link is working fine:" + respCode + " respMsg:" + respMsg);
} else if (respCode == 404) {
System.out.println(url+ " link is broken/not working fine:" + respCode + " respMsg:" + respMsg);
}
// step5 -disconnect to the URL
hc.disconnect();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.