jsoup开发指南
http://www.open-open.com/jsoup/
1、首先创建一个Weather类,用于存放一会儿抓取出来的字段
package com.bw.bean;
import lombok.Data;
@Datapublic class Weather {
private Integer wid;
private Integer cid;
private String cname;private String dates;
private String weekdays;
private String temp;
private String tip;
private String level;
}
2、创建爬取工具类,如果想将其存入数据库,只需调用改工具类,即可
package com.bw.bean;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Spider {
public List<Weather> getwlist() throws Exception{
//创建Weather数组,用于存放一会儿抓取出来的weather对象
List<Weather> wList=new ArrayList<>();
//connect(String url)
方法创建一个新的 Connection
, 和 get()
取得和解析一个HTML文件
Document doc = Jsoup.connect("http://weather.sina.com.cn/china/beijingshi/").get();
//讲抓取范围缩小到<div class="wd_city" id="wd_city">
Elements links = doc.getElementsByClass("wd_city");for (Element element : links) {
//遍历出<div class="wd_city" id="wd_city"> 中的所有a标签,查出北京下各县区的地址
Elements tag = element.getElementsByTag("a");for (int i = 0; i < tag.size(); i++) {
if(i%2!=0) {
String attr = tag.get(i).attr("href");
//进去并解析该地址下的HTML文件
Document document = Jsoup.connect(attr).get();Elements tag2 = document.getElementsByClass("blk_fc_c0_i");
for (Element element2 : tag2) {
//创建weather对象,一定要在循环中创建,若在外创建,会被最后一条数据覆盖掉,只留最后一条数据
Weather weather=new Weather();
//获取各字段下的值并赋给weather对象
String cname= element2.getElementsByClass("wt_tt0_note").text();String dates= element2.getElementsByClass("wt_fc_c0_i_date").text();
String weekdays= element2.getElementsByClass("wt_fc_c0_i_day").text();
String temp= element2.getElementsByClass("wt_fc_c0_i_temp").text();
String tip= element2.getElementsByClass("wt_fc_c0_i_tip").text();
String level= element2.getElementsByClass("wt_fc_c0_i_level level_bg2").text();
weather.setDates(dates);
weather.setWeekdays(weekdays);
weather.setTemp(temp);
weather.setTip(tip);
weather.setLevel(level);
weather.setCname(cname);
//将得到值得对象添加到weather数组中
wList.add(weather);}
}
}
}
//返回数组,以便调用
return wList;}
}
注:新手练手