欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

jsoup解析HTML_html/css_WEB-ITnose

程序员文章站 2022-05-28 12:00:34
...
预计阅读时间: 6 分钟

1、从字符串中解析Dom

//Parse a document from a String    static void parseDocFromString(){        String html = "    Parse a document from a String  "                  + "   

Parsed HTML into a doc.

"; //从字符串中解析dom Document doc = Jsoup.parse(html); System.out.println(doc.title()); }

使用Jsoup的parse(String html)类方法,可以从字符串中获取Document对象,然后再进行详细的解析。

2、从URL中获取Document对象

//Load a Document from a URL    static void loadDocByUrl() throws IOException{        //要请求的网址        String url = "https://libecnu.lib.ecnu.edu.cn/search~S0*chx/";        //请求参数        Map   params = new HashMap  ();        params.put("searcharg", "java");        params.put("searchtype", "t");        params.put("SORT", "DZ");        params.put("extended", "0");        Document doc = Jsoup.connect(url)                .userAgent("Mozilla")  //声明了浏览器用于 HTTP 请求的用户代理头的值                .timeout(10*1000)   //超时时间                .data(params)       //请求参数                .get();             //使用get方法,对应还有post()        System.out.println(doc.html());  //打印获取的html源码    }

connect(String url)方法将会得到一个Connection类的实例,Connection类是HttpConnection的子类,然后调用get()方法,将会发送get请求,返回一个Document对象。类似的,我们也可以通过post()获取,主要是看我们的请求类型是get还是post。如果请求需要参数,我们可以使用Map 构造参数,然后通过data(Map params)方法设置。得到Document对象后,我们就可以对其进行解析。

3、从文件中获取Document对象

当我们本地有一个html文件时,我们可以使用parse(File in, String charsetName)方法从本地文件中获取Document对象。

//Load a Document from a File    static void loadDocFromFile() throws IOException{        File inputFile = new File("input.html");        Document doc = Jsoup.parse(inputFile, "UTF-8");        System.out.println(doc.html());  //打印获取的html源码    }

最后我们在main方法中测试三种获取Document对象的方法,发现都能正常获取到Document对象。

public static void main(String[] args) throws IOException {        parseDocFromString();        loadDocByUrl();        loadDocFromFile();    }

参考文章: https://liuzhichao.com/p/1490.html

相关标签: jsoup解析HTML