package com.zdf.jsoup; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.select.Elements; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.zdf.jsoup.domain.Ticket; @Controller public class JsoupTest { @RequestMapping("/jsoupTest") public @ResponseBody List<Ticket> jsoupTest() { String url = "http://dynamic.12306.cn/otn/board/boardMore"; Connection connect = Jsoup.connect(url); try { List<Ticket> arr = new ArrayList<Ticket>(); Document document = connect.get(); Element table = document.getElementById("table_board_more"); // Elements tr = table.getElementsByTag("tr"); Elements tr = table.getElementsByTag("tr");//獲取tr for (Element element : tr) { Elements th = element.getElementsByTag("th"); // for (Element element2 : th) { // // System.out.println("hello"+element2.text()); // } Ticket ticket = new Ticket(); for (int i = 0; i < element.children().size(); i++) { ticket.setStartPlace(element.child(0).text());//出發地 ticket.setEndPlace(element.child(1).text());//目的地 } System.out.println(ticket); arr.add(ticket); } return arr; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 跳轉頁面 @RequestMapping("/") public String toVm() { return "velocity/ticket"; } }
另外解釋一下:html/text和val的區別:html
html添加帶有標籤的時候使用,text獲取文本 val是隻有當有value這個屬性的時候才能使用好比:<input type="text" value="XX"></input>這個時候使用val()java
<span>您好!</span>這個時候使用textnode
還有child和children的區別:child是一個須要寫下標,children是全部該元素的子節點,返回值爲elementsweb