TestJsoupt=newTestJsoup();
Documentdoc=t.getDocument(“http://www.weather.com.cn/html/weather/101280101.shtml”);
//根据网页链接得到结果文档
publicDocument getDocument (Stringurl){
try{
returnJsoup.connect(url).get();
}catch(IOExceptione) {
e.printStackTrace();
}
return null;
}
分析原网页中需要的数据所处的位置,以及应该使用的过滤条件进行过滤
/*
7日(今天)
中雨
22/17℃
3-4级
*/
4.根据得到的文档对象使用条件进行筛选
// 获取目标HTML代码
Elementselements1=doc.select(“[class=sky skyid lv3 on]”);
// 今天
Elementselements2=elements1.select(“h1”);
Stringtoday=elements2.get(0).text();
System.out.println(“日期为:”+today);
// 是否有雨
Elementselements4=elements1.select(“[class=wea]”);
Stringrain=elements4.get(0).text();
System.out.println(“是否有雨:”+rain);
// 高的温度
Elementselements5=elements1.select(“span”);
StringhighTemperature=elements5.get(0).text()+“°C”;
System.out.println(“最高温度”+highTemperature);
// 低的温度
Elementselements7=elements1.select(“i”);
StringlowTemperature=elements7.get(0).text();
System.out.println(“最低温度”+lowTemperature);
// 风力
Stringwind=elements7.get(1).text();
System.out.println(“风力”+wind);
根据股票数据爬取股票价格数据:
importjava.io.IOException;
importorg.jsoup.Jsoup;
importorg.jsoup.nodes.Document;
importorg.jsoup.select.Elements;
public classgupiaodata {
//根据网页链接得到结果文档
publicDocument getDocument (Stringurl){
try{
returnJsoup.connect(url).get();
}catch(IOExceptione) {
e.printStackTrace();
}
return null;
}
/*
时代出版 (600551)
已收盘 2017-11-07 14:59:59
13.12
+0.01
+0.08%
*/
public static voidmain(String[]args) {
gupiaodatagupiao=newgupiaodata();
Documentdocument=gupiao.getDocument(“https://gupiao.baidu.com/stock/sh600551.html?from=aladingpc”);
Elementselement1=document.select(“[class=stock-bets]”);
//得到股票名称
Elementselement2=element1.select(“[class=bets-name]”);
Stringname=element2.get(0).text();
System.out.println(“股票名称”+name);
//得到股票代码
Elementselement3=element2.select(“span”);
Stringcode=element3.get(0).text();
System.out.println(“股票代码”+code);
//得到股票的收盘价
Elementselement4=element1.select(“[class=_close]”);
Stringprice=element4.get(0).text();
System.out.println(“股票价格”+price);
//得到股票的涨幅值
Elementselement5=element1.select(“span”);
Stringfloatprice=element5.get(2).text();
Stringfloatpercent=element5.get(3).text();
System.out.println(“股票的涨幅为:”+floatprice+” 涨幅百分比为:”+floatpercent);
}
}
转载自:https://blog.csdn.net/ZHANGLIZENG/article/details/87854902