search

Jsoup Example

Sep 04, 2024 pm 04:55 PM
htmlhtml5HTML TutorialHTML PropertiesHTML tags

Basically, Java provides different types of libraries to the user, in which jsoup maven is one of the libraries that are provided by Java. Jsoup normally is used while we need to work with the real-time HTML pages. Jsoup provides the different types of API to fetch the different URLs and manipulates them with the help of HTML5 DOM and a selector of CSS as per requirement. By using jsoup we perform a different operation or we can say that we can write the different programs for getting the title of a web page, get a number of links from a specific web page, get a number of images from the specified web pages and we can get the metadata of URL and HTML documents.

Jsoup Overview

Jsoup is an open-source Java library utilized essentially for separating information from HTML. It additionally permits you to control and yield HTML. It has a consistent improvement line, extraordinary documentation, and a familiar and adaptable API. Jsoup can likewise be utilized to parse and fabricate XML.

Jsoup loads the page HTML and constructs the related DOM tree. This tree works the same way as the DOM in a program, offering techniques like jQuery and vanilla JavaScript to choose the cross, control text/HTML/characteristics and add/eliminate components.
Different components of Jsoup are listed below as follows.

  • Stacking: Bringing and parsing the HTML into a Document.
  • Separating: Choosing the ideal information into Elements and navigating it.
  • Removing: Getting properties, text, and HTML of hubs.
  • Changing: Adding/altering/eliminating hubs and altering their traits.

All Jsoup Examples

Now let’s see all the examples jsoup one by one as follows.

Example #1

package demo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class jsoup {
public static void main(String[] args) {
String html_code = "<title>Welcome</title>"
+ "<p>This is jsoup program</p>";
Document docu = Jsoup.parse(html_code);
System.out.println(docu.title());
Elements para = docu.getElementsByTag("p");
for (Element paragraph : para) {
System.out.println(paragraph.text());
}
}
}

Explanation

This is a simple program of Jsoup where we try to fetch the content of web pages, in the above example we write the string with HTML code and we try to fetch that string by using Jsoup library as shown in the above code. The end result of the above program we illustrated by using the following screenshot as follows.

Jsoup Example

Now let’s see the second example of Jsoup as follows.

Example #2

package com.sample;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class jsample {
public static void main(String[] args) {
Document docu;
try {
// required protocol that is http
docu = Jsoup.connect("http://google.com").get();
// title of page
String title_page = docu.title();
System.out.println("title : " + title_page);
// links
Elements links_web = docu.select("a[href]");
for (Element link : links_web) {
// href attribute
System.out.println("\n web_link : " + link.attr("href"));
System.out.println("web_text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation

By using the above code we try to find out the all hyperlinks of google.com. Here we first import the required packages and library as shown. After we write the code for HTTP protocol and how we can get the all hyperlinks for google.com as shown. The final output of the above program we illustrated by using the following screenshot as follows.

Jsoup Example

Now let’s see examples of images as follows.

Example #3

package demo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class jsample {
public static void main(String[] args) {
Document docu;
try {
docu = Jsoup.connect("http://google.com").get();
Elements web_images = docu.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
for (Element image : web_images) {
System.out.println("\nsrc : " + image.attr("src"));
System.out.println("Img_height : " + image.attr("height"));
System.out.println("Img_width : " + image.attr("width"));
System.out.println("Img_alt : " + image.attr("alt"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation

By using the above example, we try to fetch all sources of images, here we try to fetch the images of google.com as shown in the above code. After that, we write the code to fetch the height, width as shown. The final output of the above program we illustrated by using the following screenshot as follows.

Jsoup Example

Now let’s see the example of metadata as follows.

package demo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class jsample {
public static void main(String[] args) {
StringBuffer html_code = new StringBuffer();
html_code.append("");
html_code.append("");
html_code.append("");
html_code.append("<meta charset='\"UTF-8\"'>");
html_code.append("<title>Hollywood Life</title>");
html_code.append("<meta name='\"description\"' content='\"New' trends in entertainment news>");
html_code.append("<meta name='\"keywords\"' content='\"Cricket' news bollywood football>");
html_code.append("");
html_code.append("");
html_code.append("<div id="color">Blue color is here</div> />");
html_code.append("");
html_code.append("");
Document docu = Jsoup.parse(html_code.toString());
//get a description of metadata content
String des = docu.select("meta[name=description]").get(0).attr("content");
System.out.println("Meta description : " + des);
//get keyword of metadata content
String keyw = docu.select("meta[name=keywords]").first().attr("content");
System.out.println("Meta keyword : " + keyw);
String color_A = docu.getElementById("color").text();
String color_B = docu.select("div#color").get(0).text();
System.out.println(color_A);
System.out.println(color_B);
}
}

Explanation

By using the above code we try to implement the metadata in jsoup, here we write the HTML body and metadata and push by using the append function as shown. After that, we write the code for the metadata description and keyword of metadata. The final output of the above program we illustrated by using the following screenshot as follows.

Jsoup Example

Now let’s see how we can get icons as follows.

Example #4

package demo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class jsample {
public static void main(String[] args) {
StringBuffer html_code = new StringBuffer();
html_code.append("");
html_code.append("");
html_code.append("<link rel='\"icon\"' href="%5C%22http://specifiedurl.com/img.ico%5C%22">");
html_code.append("");
html_code.append("");
html_code.append("something");
html_code.append("");
html_code.append("");
Document docu = Jsoup.parse(html_code.toString());
String fav = "";
Element ele = docu.head().select("link[href~=.*\\.(ico|png)]").first();
if(ele==null){
ele = docu.head().select("meta[itemprop=image]").first();
if(ele!=null){
fav = ele.attr("content");
}
}else{
fav = ele.attr("href");
}
System.out.println(fav);
}
}

Explanation

By using the above example we try to implement the get an icon in Jsoup, here we need to specify the URL of the website that we want. After that, we also need to mention the link tag of HTML as shown. The final output of the above program we illustrated by using the following screenshot as follows.

Jsoup Example

Conclusion – Jsoup Example

We hope from this article you learn more about the Jsoup example. From the above article, we have taken in the essential idea of the jsoup example. and we also see the representation and example of Jsoup examples. From this article, we learned how and when we use the Jsoup example.

The above is the detailed content of Jsoup Example. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.