Automation QA Testing Course Content

Broken images code by Status Code using Selenium WebDriver

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 BrokenImagesTest {

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("http://the-internet.herokuapp.com/");
//click on Broken Images link
driver.findElement(By.linkText("Broken Images")).click();
//wait for the Borken Images heading element
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[class='example']>h3")));

// fetch all the images into List using findElements locator -tagName -img
List<WebElement> imagesList = driver.findElements(By.tagName("img"));
//iterate all the images using for each loop
for(WebElement img:imagesList) {
String imgsrc=img.getAttribute("src");
verifyLinks(imgsrc);
}
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.