httpclient4:[url]http://hc.apache.org/[/url]
jsoup:[url]http://www.open-open.com/jsoup[/url]
[color=red]小程序的母的是爬取天气查询页面上海当天的天气。[/color]
爬取的目标页面是http://www.weather.com.cn/weather/101020100.shtml。
程序爬取的结果:
2012-12-06白天 晴 高温 9℃ 西北风 3-4级 夜间 晴 低温 5℃ 南风 3-4级
jsoup:[url]http://www.open-open.com/jsoup[/url]
[color=red]小程序的母的是爬取天气查询页面上海当天的天气。[/color]
爬取的目标页面是http://www.weather.com.cn/weather/101020100.shtml。
程序爬取的结果:
2012-12-06白天 晴 高温 9℃ 西北风 3-4级 夜间 晴 低温 5℃ 南风 3-4级
public static String getHtml() {
String html = "";
DefaultHttpClient httpclient = new DefaultHttpClient();
// 访问的目标站点,端口和协议
HttpHost targetHost = new HttpHost("www.weather.com.cn", 80, "http");
// 代理的设置
HttpHost proxy = new HttpHost("web-proxy.***.com", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
// 目标地址
HttpGet httpget = new HttpGet("/weather/101020100.shtml");
try {
// 执行
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
html = EntityUtils.toString(entity);
// System.out.println(html);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return html;
}
@Test
public void getWeather() throws IOException {
/*
* // 直接从字符串中输入 HTML 文档 String html =
* "<html><head><title> 开源中国社区 </title></head>" +
* "<body><p> 这里是 jsoup 项目的相关文章 </p></body></html>"; Document doc =
* Jsoup.parse(html);
*
* // 从 URL 直接加载 HTML 文档 Document doc =
* Jsoup.connect("http://www.oschina.net/").get(); String title =
* doc.title();
*
* Document doc = Jsoup.connect("http://www.oschina.net/")
* .data("query", "Java") // 请求参数 .userAgent("I ’ m jsoup") // 设置
* User-Agent .cookie("auth", "token") // 设置 cookie .timeout(3000) //
* 设置连接超时时间 .post(); // 使用 POST 方法访问 URL
*/
// 从文件中加载 HTML 文档
/*
* File input = new File("C:/test.html"); Document doc =
* Jsoup.parse(input,"UTF-8","http://www.oschina.net/");
*/
/*
* Document doc = Jsoup.connect("http://athp.hp.com/portal/site/athp/")
* .get(); System.out.println("title:" + doc.title()); Elements els =
* doc.getElementsByTag("a"); System.out.println("\n\n\n" + els + "\n");
* for (Element e : els) { System.out.println(e.nodeName() + ":\t" +
* e.val()); }
*/
Document doc = Jsoup.parse(getHtml());
Elements contents = doc.select("div.weatherYubaoBox");
Elements trs = contents.get(0).getElementsByClass("yuBaoTable").get(0)
.getElementsByTag("tr");
StringBuilder sb=new StringBuilder();
sb.append(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
for (int i = 0; i < trs.size(); i++) {
Element tr = trs.get(i);
Elements tds = tr.getElementsByTag("td");
for (int j = 0; j < tds.size(); j++) {
Element td = tds.get(j);
if(i == 0 && j == 0){
continue;
}
if (i == 0 && j == 1) {
sb.append(td.html()).append(" ");
continue;
}
if (i == 1 && j == 0) {
sb.append(td.html()).append(" ");
continue;
}
sb.append(td.getElementsByTag("a").get(0).text()).append(" ");
}
}
System.out.println(sb);
}