All IT Courses 50% Off
Selenium Tutorials

Selenium Webdriver – Handling Images

Accessing Image Links

In this tutorial, we learn about Handling images using Selenium Webdriver. Image links in web pages are the links that represent an image. When we click an image it navigates to a different window or a page. Since Image links have no link texts we cannot use the By.linkText() and By.partialLinkText() to access the image links. In this case, we use either By.cssSelector or By.Xpath.

Consider the below example, to access the “Facebook” logo on the upper left portion on Facebook’s Password Recovery page. 

Selenium Webdriver – Handling Images

Now, we will create a test case step by step to understand how to access the image.

Step 1: Launch the Eclipse IDE

All IT Courses 50% Off

Step 2: Right-click on the src folder and click on the New > class.

Step 3: Enter the Class Name as (Image)

Step 4: Invoke the Google Chrome browser and set the system property to the path of your chromedriver.exe file.

Step 5: Navigate to the “Facebook” website.

Here is the complete code for above scenario:

import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.chrome.ChromeDriver;  
  
public class Image {  

 public static void main(String[] args) {  

String baseUrl = "https://www.facebook.com/login/identify/?ctx=recover";  
// TODO Auto-generated method stub  
 System.setProperty("webdriver.chrome.driver",  D:\\Drivers\\geckodriver.exe ");  
 WebDriver driver = new ChromeDriver();  

driver.get(baseUrl);
 }
}  

Step 6: Now we try to click on the “Facebook” logo on the upper left portion by inspecting its HTML code.

Selenium Webdriver – Handling Images

Note the title of a “Facebook” image.

Selenium Webdriver – Handling Images

Step 7: Write the code to handle the “Facebook” image.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Image {

    public static void main(String[] args) {

      String baseUrl = "https://www.facebook.com/login/identify/?ctx=recover";  

      System.setProperty("webdriver.chrome.driver"," D:\\Drivers\\geckodriver.exe ");

        WebDriver driver = new ChromeDriver();

        driver.get(baseUrl);

        //click on the "Facebook" logo

driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click();

//verify that we are back on Facebook's homepage

if (driver.getTitle().equals("Facebook - log in or sign up")) 

{

            System.out.println("We are back to Facebook's homepage");

        } else {

            System.out.println("We are NOT at Facebook's homepage");

        }

driver.close();

    }

}

Finding All Broken links using Selenium Webdriver

What are Broken Links?

The URLs or links which are not reachable are called broken links. The URLs or links may be down due to some server problem. Every URL will always have a status code 200 which is valid. For every different purpose, there are different HTTP status codes. 400 and 500 are the HTTP status codes for invalid requests. 400 status code mainly occur due to client-side error, and 500 status code mainly occur due to server response error. We will mostly unable to confirm whether the link is working or not until and unless we click and confirm it.

Reason to check the broken links

You should always make confirm that there are no broken links present on the website because the end-user should not land into an error page whenever they click on any link.

Manual checking for links is a boring task, and it takes a full day to verify every link present on the webpage and you will not get the same efficiency and interest as well every time. It is a time taking process to manually check for the links as each webpage may have a huge number of links and we have to repeat the manual process for all pages. To overcome this problem the automation process is a more apt solution.

Checking for Broken Links and Images

Below are the steps to check for all the broken links

  • Based on anchor tag <a> collect all the links in a web page
  • Send HTTP request for every link and read the HTTP response code
  • Based on displayed HTTP response code find out whether the link is broken or valid link
  • Repeat the same process for all the other links captured.

Code for checking the broken links on a webpage

Below is the whole Selenium WebDriver code to find the broken images.

Let’s create a test case in which we will automate the following scenarios to handle Broken Links:

  • Invoke a Google chrome browser.
  • Open URL: “https://makemysushi.com/404?”
  • Find all the broken images in the website.

Now, we will create a test case step by step to understand how to handle broken images in WebDriver.

Step 1: Create a New Java class

Name: BrokenLinkTest

Step 2: Invoke the Google Chrome browser and set the system property to the path of your chromedriver.exe file.

Here is the sample code to set Chrome driver system property:

 // System Property for Chrome Driver
System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe ");  

After that, we have to initialize the Chrome driver using ChromeDriver Class. Below is the sample code to initialize Chrome driver using ChromeDriver class.

// Instantiate a ChromeDriver class.      
WebDriver driver=new ChromeDriver();  

We will get the below code to launch the Google Chrome browser after combining both of the above codes.

System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe ");  
WebDriver driver=new ChromeDriver();  

After that, we need to navigate to the desired URL.

Below is the sample code to navigate to the desired URL:

// Launch Website  
driver.navigate().to("https://makemysushi.com/404?");  

Here is the complete code for the above scenario:

import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.chrome.ChromeDriver;  

public class BrkoenLinkTest {  
  
    public static void main(String[] args) {  
          
        // System Property for Chrome Driver   
 System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe ");  
  
        // Instantiate a ChromeDriver class.      
    WebDriver driver=new ChromeDriver();  

          // Launch Website  
driver.get("https://makemysushi.com/404?");  
     
    }    

Step 3: Now we will try to find all the broken links in a website.

Follow the below steps to locate the drop-down menu on the web page.
Open URL: https://makemysushi.com

Complete Code to find all the links

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
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 BrokenLinkTest {

public static void main(String[] args) throws MalformedURLException, IOException {

// TODO Auto-generated method stub

  System.setProperty("webdriver.chrome.driver"," D:\\Drivers\\geckodriver.exe ");

        WebDriver driver = new ChromeDriver();
       
        driver.manage().window().maximize(); //maximize window

        driver.manage().deleteAllCookies(); //delete all the cookies
        
        //dynamic wait

        driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        
        //enter Url

        driver.get("https://makemysushi.com/404?");
        
        //get the list of all the links and images

      List<WebElement> linksListdriver.findElements(By.tagName("a"));

      linksList.addAll(driver.findElements(By.tagName("img")));
      
      System.out.println("size of full links and images-->"+ linksList.size());
        
      List<WebElement> activeLinks = new ArrayList<WebElement>();
      
      //iterate linksList : exclude all the links or images which don’t have an href attribute

      for(int i=0; i<linksList.size(); i++) {

       System.out.println(linksList.get(i).getAttribute("href"));

if(linksList.get(i).getAttribute("href") !=null && 
               (!linksList.get(i).getAttribute("href").contains("javascript"))) {

       activeLinks.add(linksList.get(i));
       
       }

      }
    
         //get the size of active links list:

      System.out.println("size of active links and images-->"+ activeLinks.size());
      
      //check the href url with httpconnection api:

      for(int j=0; j<activeLinks.size(); j++) {

       HttpURLConnection connection = (HttpURLConnection) new 
                       URL(activeLinks.get(j).getAttribute("href")).openConnection();
      
       connection.connect();

       String response =connection.getResponseMessage();

       connection.disconnect();

       System.out.println(activeLinks.get(j).getAttribute("href") +"---->"+response);
       
      }
   }

}

Code Explanation

Step 1: Import Packages

In addition to default packages import below package

import java.net.HttpURLConnection;

Using the above methods in the above package we can send HTTP requests and get the HTTP response code.

Step 2: Get all the links and images in a web page

Store all the identified links and images in a list 

 List<WebElement> linksListdriver.findElements(By.tagName("a"));
      linksList.addAll(driver.findElements(By.tagName("img")));

Step 3: Identifying and validating the URL

Get href of an anchor tag

(linksList.get(i).getAttribute("href"));

Step 4: Iterate linksList: exclude all the links or images which don’t have an href attribute.

for(int i=0; i<linksList.size(); i++) {
       System.out.println(linksList.get(i).getAttribute("href"));
       if(linksList.get(i).getAttribute("href") !=null && 
                  (!linksList.get(i).getAttribute("href").contains("javascript"))) {
       activeLinks.add(linksList.get(i));

Step 5: Get the size of active links lists

 System.out.println("size of active links and images-->"+ activeLinks.size());

Step 6: Send Http request

HttpURLConnection class has methods to send HTTP request and get the HTTP response code. So, output of openConnection() method (URLConnection) is type casted to HttpURLConnection.

connection = (HttpURLConnection)(new URL(url).openConnection());

On invoking connect() method, the actual connection is established and the request is sent to the URL.
   connection.connect();

Step 7: Validating Links

We can get response code for the request by using the method getResponseCode() 

response =connection.getResponseMessage();

Based on response code we got we will try to check the link status.

Thus, we can get all the links from the web page and print whether the links are valid links or broken links.

Code for checking the broken images on a webpage

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindBrokenImages {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver"," D:\\Drivers\\geckodriver.exe ");
        WebDriver driver = new ChromeDriver();
       
        driver.manage().window().maximize(); //maximize window
        driver.get("http://google.com");

        List<WebElement> links = driver.findElements(By.tagName("img"));
        int invalidImageCount = 0; 
        for (int i = 0; i < links.size(); i++) {
            System.out.println(links.get(i));
            String linkURL=links.get(i).getAttribute("src");
            System.out.println(links.get(i).getText());
            URL url = new URL(linkURL);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestProperty("User-Agent","Chrome/23.0.1271.95");
            http.setConnectTimeout(10000);
            http.setReadTimeout(20000);
            int statusCode=http.getResponseCode();
            if(statusCode==404||statusCode==500){
             invalidImageCount=invalidImageCount+1;
                System.out.println(linkURL+"and its Status codes is:"+statusCode);
            }
        }
        System.out.println("total number of broken images are: "+invalidImageCount);
          
  }
}
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button