How to automate QRCode using ZXing API in Selenium


In this article I will explain how to automate QR code in Selenium Webdriver.

What is Bar Code?
QR Code is a machine-readable optical label that contains information about the item to which it is attached.

A QR Code consists of black squares arranged in a square grid on white background.

Selenium has limitation to automate QR code but by using third party API we can automate QR codes.

So, ZXing is one the third party API will be used to automate QR Codes.

Pre-requisites:

We need to download Zxing API from below links:

https://mvnrepository.com/artifact/com.google.zxing/javase/3.3.3
https://mvnrepository.com/artifact/com.google.zxing/core/3.3.3

You can also generate your own Bar Codes using below link:
https://barcode.tec-it.com

Now, I'm going to automate Bar code which is available on below application. https://testautomationpractice.blogspot.com/



Code Snippet:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class ReadingQRCode {
public static void main(String[] args) throws IOException, NotFoundException {
System.setProperty("webdriver.chrome.driver", "C:/Drivers/chromedriver_win32/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://testautomationpractice.blogspot.com/");
String qrCodeURL=driver.findElement(By.xpath("//*[@id=\"HTML4\"]/div[1]/img")).getAttribute("src");
System.out.println(qrCodeURL);
          URL url=new URL(qrCodeURL);
BufferedImage bufferedimage=ImageIO.read(url);
LuminanceSource luminanceSource=new BufferedImageLuminanceSource(bufferedimage);
BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(luminanceSource));
Result result =new MultiFormatReader().decode(binaryBitmap);
System.out.println(result.getText());
}
}

Followers