찾다

Jsoup 예

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 예

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 예

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 예

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 예

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 예

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.

위 내용은 Jsoup 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
HTML의 부울 속성은 무엇입니까? 몇 가지 예를 들어주십시오.HTML의 부울 속성은 무엇입니까? 몇 가지 예를 들어주십시오.Apr 25, 2025 am 12:01 AM

부울 속성은 값없이 활성화되는 HTML의 특수 속성입니다. 1. 부울 속성은 입력 상자를 비활성화하는 등의 존재 여부에 따라 요소의 동작을 제어합니다. 2. 작업 원칙은 브라우저가 구문 분석 할 때 속성의 존재에 따라 요소 동작을 변경하는 것입니다. 3. 기본 사용법은 속성을 직접 추가하는 것이며, 고급 사용량은 JavaScript를 통해 동적으로 제어 될 수 있습니다. 4. 일반적인 실수는 값을 설정해야한다고 잘못 생각하고 올바른 글쓰기 방법은 간결해야합니다. 5. 모범 사례는 코드를 간결하게 유지하고 부울 속성을 합리적으로 사용하여 웹 페이지 성능 및 사용자 경험을 최적화하는 것입니다.

HTML 코드를 어떻게 검증 할 수 있습니까?HTML 코드를 어떻게 검증 할 수 있습니까?Apr 24, 2025 am 12:04 AM

HTML 코드는 온라인 유효성 검사기, 통합 도구 및 자동화 된 프로세스를 통해 깨끗할 수 있습니다. 1) w3cmarkupvalidationservice를 사용하여 온라인으로 HTML 코드를 확인하십시오. 2) 실시간 확인을 위해 VisualStudioCode에 HTMLHINT 확장을 설치하고 구성하십시오. 3) htmltidy를 사용하여 시공 프로세스에서 HTML 파일을 자동으로 확인하고 청소하십시오.

HTML vs. CSS 및 JavaScript : 웹 기술 비교HTML vs. CSS 및 JavaScript : 웹 기술 비교Apr 23, 2025 am 12:05 AM

HTML, CSS 및 JavaScript는 최신 웹 페이지를 구축하기위한 핵심 기술입니다. 1. HTML 웹 페이지 구조를 정의합니다. 2. CSS는 웹 페이지의 모양을 담당합니다.

마크 업 언어로서의 HTML : 기능과 목적마크 업 언어로서의 HTML : 기능과 목적Apr 22, 2025 am 12:02 AM

HTML의 기능은 웹 페이지의 구조와 내용을 정의하는 것이며, 그 목적은 정보를 표시하는 표준화 된 방법을 제공하는 것입니다. 1) HTML은 타이틀 및 단락과 같은 태그 및 속성을 통해 웹 페이지의 다양한 부분을 구성합니다. 2) 콘텐츠 및 성능 분리를 지원하고 유지 보수 효율성을 향상시킵니다. 3) HTML은 확장 가능하므로 사용자 정의 태그가 SEO를 향상시킬 수 있습니다.

HTML, CSS 및 JavaScript의 미래 : 웹 개발 동향HTML, CSS 및 JavaScript의 미래 : 웹 개발 동향Apr 19, 2025 am 12:02 AM

HTML의 미래 트렌드는 의미론 및 웹 구성 요소이며 CSS의 미래 트렌드는 CSS-In-JS 및 CSShoudini이며, JavaScript의 미래 트렌드는 WebAssembly 및 서버리스입니다. 1. HTML 시맨틱은 접근성과 SEO 효과를 향상시키고 웹 구성 요소는 개발 효율성을 향상 시키지만 브라우저 호환성에주의를 기울여야합니다. 2. CSS-in-JS는 스타일 관리 유연성을 향상 시키지만 파일 크기를 증가시킬 수 있습니다. CSShoudini는 CSS 렌더링의 직접 작동을 허용합니다. 3. Webosembly는 브라우저 애플리케이션 성능을 최적화하지만 가파른 학습 곡선을 가지고 있으며 서버리스는 개발을 단순화하지만 콜드 스타트 ​​문제의 최적화가 필요합니다.

HTML : 구조, CSS : 스타일, 자바 스크립트 : 동작HTML : 구조, CSS : 스타일, 자바 스크립트 : 동작Apr 18, 2025 am 12:09 AM

웹 개발에서 HTML, CSS 및 JavaScript의 역할은 다음과 같습니다. 1. HTML은 웹 페이지 구조를 정의하고, 2. CSS는 웹 페이지 스타일을 제어하고 3. JavaScript는 동적 동작을 추가합니다. 그들은 함께 현대 웹 사이트의 프레임 워크, 미학 및 상호 작용을 구축합니다.

HTML의 미래 : 웹 디자인의 진화 및 트렌드HTML의 미래 : 웹 디자인의 진화 및 트렌드Apr 17, 2025 am 12:12 AM

HTML의 미래는 무한한 가능성으로 가득합니다. 1) 새로운 기능과 표준에는 더 많은 의미 론적 태그와 WebComponents의 인기가 포함됩니다. 2) 웹 디자인 트렌드는 반응적이고 접근 가능한 디자인을 향해 계속 발전 할 것입니다. 3) 성능 최적화는 반응 형 이미지 로딩 및 게으른로드 기술을 통해 사용자 경험을 향상시킬 것입니다.

HTML vs. CSS vs. JavaScript : 비교 개요HTML vs. CSS vs. JavaScript : 비교 개요Apr 16, 2025 am 12:04 AM

웹 개발에서 HTML, CSS 및 JavaScript의 역할은 다음과 같습니다. HTML은 컨텐츠 구조를 담당하고 CSS는 스타일을 담당하며 JavaScript는 동적 동작을 담당합니다. 1. HTML은 태그를 통해 웹 페이지 구조와 컨텐츠를 정의하여 의미를 보장합니다. 2. CSS는 선택기와 속성을 통해 웹 페이지 스타일을 제어하여 아름답고 읽기 쉽게 만듭니다. 3. JavaScript는 스크립트를 통해 웹 페이지 동작을 제어하여 동적 및 대화식 기능을 달성합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구