Table of Contents
概述
Home Web Front-end HTML Tutorial Jsoup代码解读之一-概述_html/css_WEB-ITnose

Jsoup代码解读之一-概述_html/css_WEB-ITnose

Jun 24, 2016 am 11:27 AM

今天看到一个用python写的抽取正文的东东,美滋滋的用Java实现了一番,放到了webmagic里,然后发现Jsoup里已经有了…觉得自己各种不靠谱啊!算了,静下心来学学好东西吧!

Jsoup是Java世界用作html解析和过滤的不二之选。支持将html解析为DOM树、支持CSS Selector形式选择、支持html过滤,本身还附带了一个Http下载器。从今天开始会写一个Jsoup源码解读系列,比起之前的博客,尽量会写的详尽一些。

概述

Jsoup的代码相当简洁,Jsoup总共53个类,且没有任何第三方包的依赖,对比最终发行包9.8M的SAXON,实在算得上是短小精悍了。

jsoup

├── examples #样例,包括一个将html转为纯文本和一个抽取所有链接地址的例子。

├── helper #一些工具类,包括读取数据、处理连接以及字符串转换的工具

├── nodes #DOM节点定义

├── parser #解析html并转换为DOM树

├── safety #安全相关,包括白名单及html过滤

└── select #选择器,支持CSS Selector以及NodeVisitor格式的遍历

使用

Jsoup的入口是Jsoup类。examples包里提供了两个例子,解析html后,分别用CSS Selector以及NodeVisitor来操作Dom元素。

这里用ListLinks里的例子来说明如何调用Jsoup:

public static void main(String[] args) throws IOException { Validate.isTrue(args.length == 1, "usage: supply url to fetch"); String url = args[0]; print("Fetching %s...", url);// 下载url并解析成html DOM结构 Document doc = Jsoup.connect(url).get(); // 使用select方法选择元素,参数是CSS Selector表达式 Elements links = doc.select("a[href]");print("\nLinks: (%d)", links.size()); for (Element link : links) { //使用abs:前缀取绝对url地址 print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); }}
Copy after login

Jsoup使用了自己的一套DOM代码体系,这里的Elements、Element等虽然名字和概念都与Java XML APIorg.w3c.dom类似,但并没有代码层面的关系。就是说你想用XML的一套API来操作Jsoup的结果是办不到的,但是正因为如此,才使得Jsoup可以抛弃xml里一些繁琐的API,使得代码更加简单。

还有一种方式是通过NodeVisitor来遍历DOM树,这个在对整个html做分析和替换时比较有用:

public interface NodeVisitor {//遍历到节点开始时,调用此方法 public void head(Node node, int depth);//遍历到节点结束时(所有子节点都已遍历完),调用此方法 public void tail(Node node, int depth);}HtmlToPlainText的例子说明了如何使用NodeVisitor来遍历DOM树,将html转化为纯文本,并将需要换行的标签替换为换行\n:public static void main(String... args) throws IOException { Validate.isTrue(args.length == 1, "usage: supply url to fetch"); String url = args[0];// fetch the specified URL and parse to a HTML DOM Document doc = Jsoup.connect(url).get();HtmlToPlainText formatter = new HtmlToPlainText(); String plainText = formatter.getPlainText(doc); System.out.println(plainText);}public String getPlainText(Element element) { //自定义一个NodeVisitor - FormattingVisitor FormattingVisitor formatter = new FormattingVisitor(); //使用NodeTraversor来装载FormattingVisitor NodeTraversor traversor = new NodeTraversor(formatter); //进行遍历 traversor.traverse(element); return formatter.toString();}
Copy after login

下一节将从DOM结构开始对Jsoup代码进行分析。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

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

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

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

See all articles