Java抓取网页信息[例子是抓取双色球某一天的信息]

本文介绍了一个简单的Java程序,该程序利用JSoup和HttpClient从网页中抓取双色球彩票信息。通过解析HTML文档并选取特定元素,程序能够准确地获取所需的红球和蓝球号码。

项目中本是根据html模板进行信息填充,第一次接触,觉得挺好玩的,网上淘淘,就有的是进行网页信息抓取,看到一个抓取双色球信息的,稍加改造下,写着试试手。

用到的是一个jsoup.jar 我用的是1.3.3版本以及一个httpclient.jar

jsoup中document抓取我看就类似Jquery方法,学过Jquery的那就很容易上手了

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GetDataFromWeb {
public void getDataFromHtml(String filepath){
	try {
		HttpClient client = new HttpClient(); 
		HttpMethod getMethod = new GetMethod(filepath);
		client.executeMethod(getMethod);
		//打印服务器返回的状态
	       System.out.println(getMethod.getStatusLine());
	      //打印返回的信息
	      StringBuffer sbf = new StringBuffer(getMethod.getResponseBodyAsString());
	      //释放连接
	      getMethod.releaseConnection();
		File file = new File("c:\\pdf\\temp.html");
		file.createNewFile();
        // 将内容插入
		PrintStream printStream = new PrintStream(new FileOutputStream(file));  
		printStream.println(sbf.toString());//将字符串写入文件   
		Document doc = Jsoup.parse(file, "utf-8", "");
		Elements redBall =doc.select("#draw_list .ball_1");
		for(int i=0;i<6;i++){
			System.out.println(redBall.get(i).html());//只取前6个最新的红球
		}
		Element buleBall =doc.select("#draw_list .ball_2").first();//只取第一个最新的蓝球
		System.out.println(buleBall.html());
		
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
public static void main(String[] args) {
	new GetDataFromWeb().getDataFromHtml("http://baidu.lehecai.com/lottery/draw/list/50?lottery_type=50&page=1&ds=2011-01-01&de=2012-07-18");
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值