ホームページ  >  記事  >  ウェブフロントエンド  >  jsoup は HTML_html/css_WEB-ITnose を解析します

jsoup は HTML_html/css_WEB-ITnose を解析します

WBOY
WBOYオリジナル
2016-06-24 11:14:58876ブラウズ

推定読了時間: 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 クラスのインスタンスを取得し、次に get() メソッドを呼び出します。 get リクエストを返し、Document オブジェクトを返します。同様に、主にリクエスト タイプが get か post かに応じて、post() を通じて取得することもできます。リクエストにパラメータが必要な場合は、Map d16797201dccc1fe78d0eb13fa114786 を使用してパラメータを構築し、data(Map d16797201dccc1fe78d0eb13fa114786 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 オブジェクトを取得する 3 つのメソッドをテストしたところ、正常に Document オブジェクトが取得できることがわかりました。

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

参考記事:https://liuzhichao.com/p/1490.html

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。