在Java代碼中解析html,獲得其中的值

來源:互聯網
上載者:User

有時我們擷取到了頁面需要在Java代碼中進行解析,擷取html中的資料,Jsoup是一個很方便的工具.

一、什麼是Jsoup。

     官網網站:http://jsoup.org/      

     可在官網下載對應的jar

     通俗的將Jsoup就是一個解析網頁的東西

二、樣本

1.頁面,通過查詢擷取到了一些資料:

2.源碼,這是一個table,class="list",通過這些來唯一標識它


3.代碼,將html以String的形式傳進來,使用Jsoup進行解析:

import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public calss MyTest {public static void demo1(String htmltest) {        String html = htmltest;        Document doc = Jsoup.parse(html);        Elements rows = doc.select("table[class=list]").get(0).select("tr");        if (rows.size() == 1) {            System.out.println("沒有結果");        }else {            System.out.println("--------------------------- 查詢結果 ---------------------------");            Element row = rows.get(1);            System.out.println("暫存單號:" + row.select("td").get(0).text());            System.out.println("投保單號:" + row.select("td").get(1).text());            System.out.println("保單號:" + row.select("td").get(2).text());            System.out.println("投保人:" + row.select("td").get(3).text());            System.out.println("被保險人:" + row.select("td").get(4).text());            System.out.println("號牌號碼:" + row.select("td").get(5).text());            System.out.println("車架號:" + row.select("td").get(6).text());            System.out.println("錄單人:" + row.select("td").get(7).text());            System.out.println("投保日期:" + row.select("td").get(8).text());            System.out.println("暫存單狀態:" + row.select("td").get(9).text());            System.out.println("狀態:" + row.select("td").get(10).text());            System.out.println("-----------------------------------------------------------------");        }    }}



4.輸出結果:


更多的使用方法可以去詳細閱讀Jsoup的API

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.