import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; 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.firefox.FirefoxDriver; public class Findbrokenimages { static int statusCode; public static void main(String args[]) throws IOException { // WebDriver reference but Firefox object WebDriver driver = new FirefoxDriver(); //Maximize browser window driver.manage().window().maximize(); //Go to page URL which page / url want to find out invalid or broken driver.get("http://www.google.com"); //Set timeout driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Store all image tag imagetags array List<WebElement> imagetags = driver.findElements(By.tagName("img")); for (WebElement imtag : imagetags) { if (!(imtag.getAttribute("src").trim() == null) && !(imtag.getAttribute("src").equals(""))) { //Get status code statusCode = getResponseCode(imtag.getAttribute("src").trim()); // Invalid or Broken image if (statusCode == 404) { System.out.println("Invalid or Broken image url # " + imtag.getAttribute("src").trim()); } } } //close firefox browser driver.quit(); } // Return status code public static int getResponseCode(String urlString) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.connect(); return huc.getResponseCode(); } }
How to find out broken or invalid images in Selenium Webdriver using java.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment