Java中使用jsoup进行HTML解析和提取


=Start=

缘由:

在整理如何使用Java发起HTTP请求的过程中,发现了一篇内容非常详细的文章,其在最后附带了一个「Parsing and extracting HTML」的内容,刚好是我比较感兴趣和需要的内容,所以实际验证测试了一遍之后在此整理出来,方便以后参考和使用。

正文:

参考解答:

几乎所有已知的HTML解析器都实现了W3C的DOM API(是JAXP API(Java提供的用于进行XML处理的API)的一部分),并返回给你一个org.w3c.dom.Document文档对象——可直接被JAXP API使用。主要的不同之处在于各自的特性上面。

一般来说:

现在(各HTML解析器)各自的优缺点应该已经足够清楚了。如果你只是想使用标注的JAXP API进行遍历,使用第一类即可(具体根据你的需求和它们的各自特点还有库的健壮性进行选择);如果要对HTML做单测,请选择第二类HtmlUnit;如果要从HTML中提取特定的数据,选择Jsoup吧。

package com.ixyzero.learn.utils;

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

/**
 * Created by ixyzero on 2019/5/11.
 */
public class JsoupTest {
    public static void main(String[] args) throws Exception {
        String url = "https://stackoverflow.com/questions/2835505";
        Document document = Jsoup.connect(url).get();

        String question = document.select("#question .post-text").text();
        System.out.println("Question: " + question);
        System.out.println();

        Elements answerers = document.select("#answers .user-details a");
        for (Element answerer : answerers) {
            System.out.println("Answerer: " + answerer.text());
        }
        System.out.println();


        // 使用链式的 .userAgent/.timeout 进行特定设置
        Document doc = Jsoup.connect("https://www.google.com.hk/search?num=100&site=&source=hp&q=filetype%3Ajsp&oq=filetype%3Ajsp")
                            .userAgent("Googlebot/2.1 (+http://www.googlebot.com/bot.html)")
                            .timeout(5000)
                            .get();
        // System.out.println(doc);
        // System.out.println(doc.getElementsByTag("cite"));

        Elements element = doc.getElementsByTag("cite");
        for (Element e: element) {
            System.out.println(e.text());
        }
    }

}

更多更详细的用法可以参考「jsoup的官方文档」以及「JSoup快速入门」一文,根据自己的实际需求进行选用。

参考链接:

=END=


《“Java中使用jsoup进行HTML解析和提取”》 有 6 条评论

  1. Google搜索结果页面中的链接地址的jQuery选择器
    https://www.google.com.hk/search?num=100&site=&source=hp&q=filetype%3Ajsp&oq=filetype%3Ajsp
    `
    — 先通过GET参数设定搜索结果个数为100

    #rso > div > div > div:nth-child(1) > div > div > div.r > a:nth-child(1) > div > cite
    #rso > div > div > div:nth-child(2) > div > div > div.r > a:nth-child(1) > div > cite

    #rso > div > div > div:nth-child(101) > div > div > div.r > a:nth-child(1) > div > cite

    — JS Path
    document.querySelector(‘#rso > div > div > div:nth-child(101) > div > div > div.r > a:nth-child(1) > div > cite’)

    — XPath
    //*[@id=”rso”]/div/div/div[100]/div/div/div[1]/a[1]/div/cite
    `

  2. Java Jsoup 如何将获取到的内容存成HTML文件?
    https://stackoverflow.com/questions/24696766/how-to-save-a-jsoup-document-to-an-html-file
    `
    // 为了避免jsoup进行过滤,请使用下面的方式来获取原始HTML内容
    Connection.Response html = Jsoup.connect(“PUT_URL_HERE”).execute();
    System.out.println(html.body());

    // 另一种方法
    // https://mvnrepository.com/artifact/commons-io/commons-io
    import org.apache.commons.io.FileUtils;

    public void downloadPage() throws Exception {
    final Response response = Jsoup.connect(“http://www.example.net”).execute();
    final Document doc = response.parse();

    final File f = new File(“filename.html”);
    FileUtils.writeStringToFile(f, doc.outerHtml(), “UTF-8”);
    }
    `

  3. Jsoup HTML parser – Tutorial & examples
    https://aboullaite.me/jsoup-html-parser-tutorial-examples/
    `
    1- Parsing a HTML string
    2- Parsing a local HTML file
    3- Reading a web site’s title
    4- Reading HTML source
    5- Getting meta information
    5- Parsing links
    6- Sanitizing HTML data
    7- Grabs All Images
    8- Get form attributes in html page
    9- Performing a Google search
    `

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注