利用jsoup解析天氣預報

java的一個開源的解析Html的程序jsoup將html進行解析,並且讓我們可以像對css操作一樣來獲取解析之後的內容,本文即利用其特性進行解析

jsoup的開源jar包請自行下載

public class WeatherInfo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        getCityWeatherInfo();
        //getCityAndUrl();
    }
    /**
     * Jsoup.connect例子
     * 獲取天氣預報網網頁,並且解析出天氣現象  氣溫  風向  風力
     */
    public static void getCityWeatherInfo(){
        Document doc;
        
        String str2 = "http://www.weather.com.cn/html/weather/101190101.shtml";
        try {
            doc = Jsoup.connect(str2).get();
            Elements content = doc.getElementsByClass("yuBaoTable"); 
            for (Element link : content) {
              String linkText = link.text();
              String[] strs = linkText.split(" ");
              for (String s : strs){
                  System.out.print(s+"\t");
              }
              System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 獲取每個省份中的城市及其對應的連接
     */
    public static void getCityAndUrl(){
        Document doc;
        String str2 = "http://www.weather.com.cn/guangdong/index.shtml";
        try {
            doc = Jsoup.connect(str2).get();
            Element content = doc.getElementById("forecastID"); 
           
            Elements es = content.children();
            for( Element e : es ){
                Node node = e.childNode(0).childNode(0);
                
                System.out.print(node.childNode(0)+ "\t");
                System.out.println(node.attr("href"));
            }
           
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

jsoup中文開發手冊:http://www.open-open.com/jsoup/

jsoup   主頁:http://jsoup.org/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章