java三方---->html解析jsoup的使用

  jsoup 是一款 Java 的HTML 解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据。今天我们就开始jsoup的学习。

jsoup解析html

jsoup的主要功能如下:

  • 从一个URL,文件或字符串中解析HTML;

  • 使用DOM或CSS选择器来查找、取出数据;

  • 可操作HTML元素、属性、文本;

 jsoup测试项目的结构如下,首先要下载jsoup的jar包:https://jsoup.org/download

一、 JsoupTest中我们从网址、文件和字符串中解析html。

package com.huhx.jsoup;

import java.io.File;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class JsoupTest {
    static String html = "<html><head><title>First parse</title></head>"
            + "<body><p id='parseHtml'><font>Parsed HTML into a doc.</font></p></body></html>";

    static String fileName = "file/jsoup.html";
    static String url = "http://www.baidu.com";

    // 从url中解析
    public static void readFromUrl(String url) {
        try {
            Document document = Jsoup.connect(url).get();
            System.out.println(document.title());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件中解析
    public static void readFromFile(String file) {
        File input = new File(file);
        try {
            Document document = Jsoup.parse(input, "UTF-8", "");
            System.out.println(document.getElementsByTag("p").text()); // 通过tag名得到元素
            System.out.println(document.getElementById("divid").text()); // 通过id
            System.out.println(document.getElementsByClass("divclass").attr("id")); // 通过class
            System.out.println(document.getElementsByAttribute("href").attr("id")); // 通过属性

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从字符串中解析
    public static void readFromString(String string) {
        Document document = Jsoup.parse(string);
        Elements element = document.getElementsByTag("p");
        System.out.println(element.text());
        System.out.println(element.html());
        System.out.println(element.attr("id"));
    }

    public static void main(String[] args) {
        readFromString(html);
        System.out.println("------------------------------------------------------------");
        readFromFile(fileName);
        System.out.println("------------------------------------------------------------");
        readFromUrl(url);
    }
}

二、 jsoup.html的内容如下:

<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
    <p>
        <font>Hello World.</font>
    </p>
    <div id="divid">huhx div id</div>
    <div class="divclass" id="divclassid">huhx div class</div>
    <a href="http://huhx.com" id="huhx">Hello huhx</a>
</body>
</html>

三、运行结果如下:

Parsed HTML into a doc.
<font>Parsed HTML into a doc.</font>
parseHtml
------------------------------------------------------------
Hello World.
huhx div id
divclassid
huhx
------------------------------------------------------------
百度一下,你就知道

友情链接

原文地址:https://www.cnblogs.com/huhx/p/javaThirdJsoup.html