Web Scraping in Java With Jsoup
Last Updated :
21 Mar, 2024
Web scraping means the process of extracting data from websites. It's a valuable method for collecting data from the various online sources. Jsoup is a Java library that makes handling HTML content easier. Let's learn how to build a basic web scraper with Jsoup.
Prerequisites
Here's what you need to use in:
Concept
Jsoup helps us to read HTML documents. It lets us follow the document's structure and extract the data we want. We use CSS selectors or DOM traversal methods for this. With Jsoup, we go to a website, get its HTML, and take out things like text, links or images.
Step-by-Step Implementation
Now, let's create a basic Java project using Maven.
Step 1: Create a Java Maven project
Open the cmd/terminal and run the following commands to create a new Maven project.
mvn archetype:generate
-DgroupId=com.example
-DartifactId=java-jsoup1
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false

This command will generate a basic Maven project structure. Below we can see the Maven project builds successfully.
Step 2: Add Jsoup Dependency
Open the pom.xml file in the project folder then add the Jsoup dependency into it and save the file.
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
</dependencies>
Step 3: Create a Java File
In the src/main/java/com/example folder, create a Java file named MyScrapper.java.
Java
package com.example;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class MyScrapper {
public static void main(String[] args)
{
try {
Document doc
= Jsoup
.connect("https://geeksforgeeks.org/")
.get();
Elements links = doc.select("a[href]");
Elements images = doc.select("img[src]");
System.out.println("Links: ");
for (Element link : links) {
System.out.println(link.attr("href"));
}
System.out.println("\n-----\n");
System.out.println("Images:");
for (Element image : images) {
System.out.println(image.attr("src"));
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
- Firstly We declare that the class is part of the com.example package.
- After that, we import those classes we need from Jsoup library and java.io package.
- Then created a class named MyScrapper with the main mthod because its the entry point of the program. and it throws an IOException. This shows that input/output exceptions could happen.
- We use Jsoup.connect("https://geeksforgeeks.org/").get() to establish a connection to the website and fetch its HTML content as a Document object.
- Selecting Elements:
- doc.select("a[href]") selects all anchor elements (<a>) with an href attribute and stores them in the links variable.
- doc.select("img[src]") selects all image elements (<img>) with a src attribute and stores them in the images variable.
- And at last, the extracted values are printed to the console.
Step 4: Run the Program
To run the project, use below maven commands.
mvn compile
mvn exec:java -Dexec.mainClass="com.example.MyScrapper"
Note: The project can be direct run by presssing the run icon in the IDE.
Output:
In this article will teach you how to make a basic web scraper using Jsoup in Java. Make sure to follow website rules and scrape responsibly and fairly.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read