java用jsoup爬网页数据_java使用jsoup按指定元素位置爬取网页信息

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值