×

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement it. This

Web Crawler Definition

A web crawler is essentially an application used mostly for web navigation and page discovery so that new or newly created pages can be found and indexed. The crawler explores wide and deep to extract hyperlinks, starting with a variety of seed websites or well-known URLs.

The Breadth-First Search Algorithm's web crawler is one of its most crucial applications. A directed graph is supposed to be able to represent the entire internet.

The web crawler needs to be robust and kind. Here, being polite involves abiding by robots.txt directives and avoiding making repeated website visits. The term "robust" refers to the capacity to avoid harmful conduct and spider webs.

The below is the procedure followed to create a web crawler

  • We choose a URL out from frontier in the first phase.
  • Obtain the URL's HTML code.
  • By interpreting the HTML code, you can obtain the urls to the other URLs.
  • Verify whether or not the URL has already been crawled. We also determine whether we have already seen the same content. Then add them to that same index if neither condition matches.
  • Check to see if each extracted URL consents to being examined (robots.txt, crawling frequency).

Note:  This code will not work on an online IDE due to proxy issues. Try to run on your local computer.

Distinctions among data crawling and data scraping

Both data crawling as well as data scraping are crucial ideas in data processing. Data crawling entails working with big data sets and creating a custom crawler that can reach even the most buried web pages. Data extraction from any source is known as data scraping.

Data CrawlingData Scraping
Data is solely extracted from the web via data crawling.Data extraction from any source, including the web, is known as data scraping.
Duplication is a fundamental component of data crawling.Duplication is not always an element of data scraping.
Most of it is carried out on a big volume.Any scale, whether small or huge, can be used.
Just a crawl agent is needed.Both the search crawler and the agent are necessary.

Let us understand the concept with an example program

File name: Webcrawl.java

// Example program for java web crawler
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


//This class holds the methods needed by the web crawler
class WebCrowler {


// to keep the Links in the BFS  required FIFO sequence
private Queue<String> queue;


// To save visited Links
private HashSet<String>
discovered_websites;


// Constructor for setting up the necessary variables
public WebCrowler()
{
this.queue
= new LinkedList<>();


this.discovered_websites
= new HashSet<>();
}


// a method to launch the BFS and find all URLs
public void discover(String root)
{
// preserving the base URL to launch BFS
this.queue.add(root);
this.discovered_websites.add(root);


// till the queue is empty, it will loop.
while (!queue.isEmpty()) {


// To save the URL that is now in the lead of the queue
String v = queue.remove();


// to save the website's unprocessed HTML
String raw = readUrl(v);


// Using regular expressions with URLs
String regex
= "https://(\\w+\\.)*(\\w+)";


// To save the URL pattern created using regex
Pattern pattern
= Pattern.compile(regex);


// To extract all the URL that
// matches the pattern in raw
Matcher matcher
= pattern.matcher(raw);


// It will loop until all the URLs
// in the current website get stored
// in the queue
while (matcher.find()) {


// To store the next URL in raw
String actual = matcher.group();


// It will check whether this URL is
// visited or not
if (!discovered_websites
.contains(actual)) {


// If not visited it will add
// this URL in queue, print it
// and mark it as visited
discovered_websites
.add(actual);
System.out.println(
"webpage accessed: "
+ actual);


queue.add(actual);
}
}
}
}


// Function to return the raw HTML
// of the current website
public String readUrl(String v)
{


// Initializing empty string
String raw = "";


// If this code throws any exceptions, handle them in a try-catch statement.
try {
// Change the string in the URL
URL url = new URL(v);


// Website HTML should be read
BufferedReader be
= new BufferedReader(
new InputStreamReader(
url.openStream()));


// In order to save website input
String input = "";


// line for line through the HTML and add it to raw
while ((input
= br.readLine())
!= null) {
raw += input;
}
br.close();
}


catch (Exception ex) {
ex.printStackTrace();
}


return raw;
}
}
public class Webcrawl {
 
public static void main(String[] args)
{
//The object has been created
WebCrowler web_crowler
= new WebCrowler();
String root
= "https:// www.google.com";
web_crowler.discover(root);
}
}

Output

webpage accessed: https://www.google.com
webpage accessed: https://www.facebook.com
webpage accessed: https://www.amazon.com
webpage accessed: https://www.microsoft.com
webpage accessed: https://www.apple.com

Related Topics

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.