Home  >  Article  >  Web Front-end  >  jsoup解析HTML_html/css_WEB-ITnose

jsoup解析HTML_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:14:58875browse

预计阅读时间: 6 分钟

1、从字符串中解析Dom

//Parse a document from a String    static void parseDocFromString(){        String html = " <html>  <head>  <title> Parse a document from a String </title>  </head> "                  + " <body>  <p> Parsed HTML into a doc. </p>  </body>  </html> ";        //从字符串中解析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 <String, String>  params = new HashMap <String, String> ();        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

Statement:
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