package task;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Crawler {
//1.成员变量
private static String outputfile = "output\\天气预报数据.txt";
private static String sourcefile = "resource/北京历史天气预报查询.htm";
//2.解析本地网页,返回Document
public static Document getHtml() throws IOException {
File f=new File(sourcefile); //创建文件对象
//解析本地文件,第一个参数是文件对象
//第二个参数是网页的字符编码格式
Document doc=Jsoup.parse(f,"gbk");
return doc;
}
//3.提取数据,返回集合
public static ArrayList<EntityBean> getData(Document doc) throws IOException {
//利用selector选择器,提取32行数据
Elements trs=doc.select("#content > table > tbody > tr");
ArrayList<EntityBean> list=new ArrayList<EntityBean>();//创建集合对象
for(Element tr : trs) {
//获取tr,每一行的前6列数据
String date=tr.child(0).text();
String tqzk=tr.child(1).text();
String qw=tr.child(2).text();
String flfx=tr.child(3).text();
//每行数据创建一个对应的实例化对象ed
EntityBean eb=new EntityBean(date,tqzk,qw,flfx);
//System.out.println(eb.toString());
list.add(eb);//将每一行天气数据对象放进集合
}
return list;
}
//4.写出到本地文件系统
public static void wirteToFile(ArrayList<EntityBean> ebs) throws FileNotFoundException {
PrintWriter pw=new PrintWriter(outputfile);//创建字节打印流对象
for(EntityBean eb : ebs) {
pw.println(eb.getDate()+"\t"+eb.getTqzk()+"\t"+eb.getQw()+
"\t"+eb.getFlfx());
}
pw.close();
}
//5.主方法
public static void main(String[] args) throws IOException {
Document doc = Crawler.getHtml();//解析网页,得到doc对象
System.out.println("网页标题:"+doc.title());
ArrayList<EntityBean> entitys = Crawler.getData(doc); //提取数据
Crawler.wirteToFile(entitys);
}
}
package task;
public class EntityBean {
//成员变量列表
private String date;
private String tqzk;
private String qw;
private String flfx;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTqzk() {
return tqzk;
}
public void setTqzk(String tqzk) {
this.tqzk = tqzk;
}
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getFlfx() {
return flfx;
}
public void setFlfx(String flfx) {
this.flfx = flfx;
}
public EntityBean(String date, String tqzk, String qw, String flfx) {
super();
this.date = date;
this.tqzk = tqzk;
this.qw = qw;
this.flfx = flfx;
}
public EntityBean() {
super();
}
@Override
public String toString() {
return "EntityBean [date=" + date + ", tqzk=" + tqzk + ", qw=" + qw + ", flfx=" + flfx + "]";
}
//无参构造方法
//有参构造方法
//get()方法和set()方法
//重写toString()方法
}