Java通过jsoup实现网页天气数据解析

本文介绍了一个使用Java和Jsoup库从指定网站抓取并解析天气数据的方法。通过发送HTTP请求,获取包含天气信息的XML数据,并从中提取城市、日期、温度等关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


public class WeatherTest {

	/**Java通过jsoup实现网页天气数据解析
	 * @param args
	 * @throws Exception 
	 * @throws UnsupportedEncodingException 
	 * @throws MalformedURLException 
	 */
	public static void main(String[] args) throws MalformedURLException, UnsupportedEncodingException, Exception {
		Document doc = getURLContent("http://www.soso.com/tb.q?cid=webq.wea");
		String content = doc.html();
		int beginLocal = content.indexOf("<xml id=\"WeatherData\" style=\"display:none\"> ");
		int endLocal = content.indexOf("</xml>");
		content = content.substring(beginLocal, endLocal);
		
		String cityStr = getXMLVarByName("<city>","</city>",content);
		System.out.println("城市:"+cityStr);
		
		String dateStr = getXMLVarByName("<date>","</date>",content);
		System.out.println("日期:"+dateStr);
		
		String todayTemperature = getXMLVarByName("<temperature>","</temperature>",content);
		System.out.println("今日气温:"+todayTemperature);
		
		String todayWeather = getXMLVarByName("<weather>","</weather>",content);
		System.out.println("今日天气:"+todayWeather);
		
		String todayWind = getXMLVarByName("<wind>","</wind>",content);
		System.out.println("今日风向:"+todayWind);
	}
	/**
	 * 获取xml格式的信息
	 * @param name
	 * @param content
	 * @return
	 */
	private static String getXMLVarByName(String startStr, String endStr,String content){
		String xmlData = content;		
		int begin = xmlData.indexOf(startStr);		
		int end = xmlData.indexOf(endStr);		
		String result=xmlData.substring(begin+startStr.length(),end);
		result = result.trim();		
		return result;
	}
/**
 * 获取网页
 * @param docUrl
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
	private static Document getURLContent(String docUrl) throws MalformedURLException, IOException, UnsupportedEncodingException {
		Document doc = Jsoup.connect(docUrl)
		  .data("query", "Java")
		  .userAgent("Mozilla")
		  .cookie("auth", "token")
		  .timeout(3000)
		  .post();
		return doc;
	}
}

 需要jsoup的jar包,在附件上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值