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/
转载于:https://blog.51cto.com/fblsky/1438081