项目中本是根据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");
}
}

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

被折叠的 条评论
为什么被折叠?



