ASP.NET获取天气预报大致分析有 1到某个网站上分析网站的代码获取;2自己写驱动服务和web服务 第二种水太深不曾涉及。
ASP.NET后台程序获取中央气象台天气预报
1.天气封装成一个实体
2.可以获取当天天气,也可以获取未来五天的天气集合
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
namespace CommonComponents
{
/// <summary>
/// 天气辅助类
/// </summary>
public class TqHelper
{
/// <summary>
/// 获取未来五天天气
/// </summary>
/// <param name="citycode">城市编号(例如:[url]http://www.weather.com.cn/html/weather/101010100.shtml[/url]中的“101010100”就是编号)</param>
/// <returns>未来五天的天气实体集合</returns>
public List<TqInfo> GetFiveDayTqList(string citycode)
{
List<TqInfo> tqInfoList = null;
Hashtable ht = GetTqHash(citycode);
if (ht!=null && ht.Count > 0)
{
tqInfoList = new List<TqInfo>();
for (int i = 1; i <= 5; i++)
{
TqInfo tqInfo = new TqInfo();
tqInfo.City = ht["city"].ToString();
tqInfo.CityEN = ht["city_en"].ToString();
tqInfo.CityID = ht["cityid"].ToString();
double temp1 = Convert.ToDouble(ht["temp1"].ToString().Split('~')[0].Replace("℃", ""));
double temp2 = Convert.ToDouble(ht["temp1"].ToString().Split('~')[1].Replace("℃", ""));
tqInfo.MaxTemperature = temp1 >= temp2 ? temp1.ToString() + "℃" : temp2.ToString() + "℃";
tqInfo.MinTemperature = temp1 <= temp2 ? temp1.ToString() + "℃" : temp2.ToString() + "℃";
double tempF1 = Convert.ToDouble(ht["tempF1"].ToString().Split('~')[0].Replace("℉", ""));
double tempF2 = Convert.ToDouble(ht["tempF1"].ToString().Split('~')[1].Replace("℉", ""));
tqInfo.MaxTemperatureF = tempF1 >= tempF2 ? tempF1.ToString() + "℉" : tempF2.ToString() + "℉";
tqInfo.MinTemperatureF = tempF1 <= tempF2 ? tempF1.ToString() + "℉" : tempF2.ToString() + "℉";
tqInfo.Weather = ht["weather" + i.ToString()].ToString();
tqInfo.Wind = ht["wind" + i.ToString()].ToString();
tqInfoList.Add(tqInfo);
}
}
return tqInfoList;
}
/// <summary>
/// 获取当天天气
/// </summary>
/// <param name="citycode">城市编号(例如:[url]http://www.weather.com.cn/html/weather/101010100.shtml[/url]中的“101010100”就是编号)</param>
/// <returns>天气实体</returns>
public TqInfo GetTodayTq(string citycode)
{
TqInfo tqInfo = null;
Hashtable ht = GetTqHash(citycode);
if (ht != null && ht.Count > 0)
{
tqInfo = new TqInfo();
tqInfo.City = ht["city"].ToString();
tqInfo.CityEN = ht["city_en"].ToString();
tqInfo.CityID = ht["cityid"].ToString();
double temp1 = Convert.ToDouble(ht["temp1"].ToString().Split('~')[0].Replace("℃", ""));
double temp2 = Convert.ToDouble(ht["temp1"].ToString().Split('~')[1].Replace("℃", ""));
tqInfo.MaxTemperature = temp1 >= temp2 ? temp1.ToString() + "℃" : temp2.ToString() + "℃";
tqInfo.MinTemperature = temp1 <= temp2 ? temp1.ToString() + "℃" : temp2.ToString() + "℃";
double tempF1 = Convert.ToDouble(ht["tempF1"].ToString().Split('~')[0].Replace("℉", ""));
double tempF2 = Convert.ToDouble(ht["tempF1"].ToString().Split('~')[1].Replace("℉", ""));
tqInfo.MaxTemperatureF = tempF1 >= tempF2 ? tempF1.ToString() + "℉" : tempF2.ToString() + "℉";
tqInfo.MinTemperatureF = tempF1 <= tempF2 ? tempF1.ToString() + "℉" : tempF2.ToString() + "℉";
tqInfo.Weather = ht["weather1"].ToString();
tqInfo.Wind = ht["wind1"].ToString();
}
return tqInfo;
}
/// <summary>
/// 获取天气预报键值对(包括未来五天的)
/// </summary>
/// <param name="citycode">城市编号(例如:[url]http://www.weather.com.cn/html/weather/101010100.shtml[/url]中的“101010100”就是编号)</param>
/// <returns>哈希表键值对</returns>
public Hashtable GetTqHash(string citycode)
{
Hashtable ht = new Hashtable();
string tqstr = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://m.weather.com.cn/data/"+citycode+".html");
request.Method = "Get";
request.ContentType = "application/x-www-form-urlencoded ";
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.UTF8);
tqstr = sr.ReadToEnd();
tqstr = tqstr.Replace("{/"weatherinfo/":{", "").Replace("}}", "").Replace("/"", "");
string[] tqlist = tqstr.Split(',');
for(int i=0;i<tqlist.Length;i++)
{
string []tqtemp = tqlist[i].Split(':');
ht.Add(tqtemp[0], tqtemp[1]);
}
return ht;
}
}
/// <summary>
/// 每日天气实体
/// </summary>
public class TqInfo
{
/// <summary>
/// 城市中文名
/// </summary>
private string _city;
/// <summary>
/// 城市编号
/// </summary>
private string _cityid;
/// <summary>
/// 城市英文名
/// </summary>
private string _cityen;
/// <summary>
/// 最低气温
/// </summary>
private string _minTemperature;
/// <summary>
/// 最高气温
/// </summary>
private string _maxTemperature;
/// <summary>
/// 最低气温(华氏温度)
/// </summary>
private string _minTemperatureF;
/// <summary>
/// 最高气温(华氏温度)
/// </summary>
private string _maxTemperatureF;
/// <summary>
/// 天气情况
/// </summary>
private string _weather;
/// <summary>
/// 风向及风力
/// </summary>
private string _wind;
/// <summary>
/// 城市中文名
/// </summary>
public string City
{
get { return _city; }
set { _city = value; }
}
/// <summary>
/// 城市编号
/// </summary>
public string CityID
{
get { return _cityid; }
set { _cityid = value; }
}
/// <summary>
/// 城市英文名
/// </summary>
public string CityEN
{
get { return _cityen; }
set { _cityen = value; }
}
/// <summary>
/// 最低温度
/// </summary>
public string MinTemperature
{
get { return _minTemperature; }
set { _minTemperature = value; }
}
/// <summary>
/// 最高温度
/// </summary>
public string MaxTemperature
{
get { return _maxTemperature; }
set { _maxTemperature = value; }
}
/// <summary>
/// 最低温度(华氏温度)
/// </summary>
public string MinTemperatureF
{
get { return _minTemperatureF; }
set { _minTemperatureF = value; }
}
/// <summary>
/// 最低温度(华氏温度)
/// </summary>
public string MaxTemperatureF
{
get { return _maxTemperatureF; }
set { _maxTemperatureF = value; }
}
/// <summary>
/// 天气情况
/// </summary>
public string Weather
{
get { return _weather; }
set { _weather = value; }
}
/// <summary>
/// 风向及风力
/// </summary>
public string Wind
{
get { return _wind; }
set { _wind = value; }
}
}
}
刚赶工写了一个获取新浪天气预报的功能,顺便把代码分享了出来,以后再有这样的工作,大家可以直接把代码拿来使用。
1.利用新浪提供给的iframe直接嵌入,这种方式非常的简单,但是却没有交互性。代码如下:
2.抓取当天的天气,以指定格式输出。
涉及的核心代码如下:
public static ArrayList GetWeather(string code)
{
/*
[0] "北京 "string
[1] "雷阵雨 "string
[2] "9℃" string
[3] "29℃"string
[4] "小于3级"string
*/
string html = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://weather.sina.com.cn/iframe/weather/" + code + "_w.html ");
request.Method = "Get";
//request.Timeout = 1;
request.ContentType = "application/x-www-form-urlencoded ";
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, System.Text.Encoding.GetEncoding("GB2312"));
html = sr.ReadToEnd();
s.Close();
sr.Close();
}
catch (Exception err)
{
throw new Exception("访问地址出错~~~ ");
}
int count = html.Length;
int starIndex = html.IndexOf("<table ", 0, count);
int endIndex = html.IndexOf("</table>", starIndex, count - starIndex);
html = html.Substring(starIndex, endIndex - starIndex + 8);
//得到城市
int cityStartIndex = html.IndexOf("<b>", 0, html.Length);
int cityEndIndex = html.IndexOf("</b>", 0, html.Length);
string City = html.Substring(cityStartIndex + 3, cityEndIndex - cityStartIndex - 3);
//得到天气
int weatherStartIndex = html.IndexOf("<b>", cityEndIndex);
int weatherEndIndex = html.IndexOf("</b>", weatherStartIndex);
string Weather = html.Substring(weatherStartIndex + 3, weatherEndIndex - weatherStartIndex - 3);
//得到温度
int temperatureStartIndex = html.IndexOf("<b", weatherEndIndex);
int temperatureEndIndex = html.IndexOf("</b>", weatherEndIndex + 3);
string Temperature = html.Substring(temperatureStartIndex + 21, temperatureEndIndex - temperatureStartIndex - 21);
int int1 = Temperature.IndexOf("℃", 0);
int int2 = Temperature.IndexOf("~", 0);
int int3 = Temperature.IndexOf("℃", int2);
string MinTemperature = Temperature.Substring(int2 + 1, int3 - int2);
string MaxTemperature = Temperature.Substring(0, int2 - int1 + 2);
//得到风力
int windforceStartIndex = html.IndexOf("风力:", temperatureEndIndex);
int windforceEndIndex = html.IndexOf("<br>", windforceStartIndex);
string Windforce = html.Substring(windforceStartIndex + 3, windforceEndIndex - windforceStartIndex - 3);
if (Windforce.Contains("小于") && (!Windforce.Contains("等于"))) //判断风力是否含有"小于"或"小于等于"字样将,如果有的话,将其替换为2-
{
//Windforce = Windforce.Replace("小于", "2-");
string strWindforce = Windforce.Substring(2, Windforce.Length - 3);
int minWindforce = Int32.Parse(strWindforce) - 1;
Windforce = Windforce.Replace("小于", minWindforce.ToString() + "-");
}
else if (Windforce.Contains("小于等于"))
{
string strWindforce = Windforce.Substring(4, Windforce.Length - 5);
int minWindforce = Int32.Parse(strWindforce) - 1;
Windforce = Windforce.Replace("小于等于", minWindforce.ToString() + "-");
}
ArrayList al = new ArrayList();
al.Add(City);
al.Add(Weather);
al.Add(MinTemperature);
al.Add(MaxTemperature);
al.Add(Windforce);
return al;
}
这里涉及到一个ConvertCode类,它的作用是用于把城市转换为对应的全国统一的编码,代码如下:
public static ArrayList GetThreeDayWeather(string City)
{
ArrayList al = new ArrayList();
/*
[0] "今天 北京" string
[1] "2009-04-17,星期五" string
[2] "晴转多云" string
[3] "12℃" string
[4] "25℃" string
[5] "2-3级" string
[6] "明天 北京" string
[7] "2009-04-18,星期六" string
[8] "阴转阵雨" string
[9] "11℃" string
[10] "21℃" string
[11] "2-3级" string
[12] "后天 北京" string
[13] "2009-04-19,星期日" string
[14] "多云转阵雨" string
[15] "9℃" string
[16] "20℃" string
[17] "2-3级" string
*/
string Html = ""; //返回来的网页的源码
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = string.Format("city=" + City);
byte[] data = encoding.GetBytes(postData);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://php.weather.sina.com.cn/search.php?city=" + System.Web.HttpContext.Current.Server.UrlEncode(City) + "&f=1&dpc=1");
request.Method = "Get";
request.ContentType = "application/x-www-form-urlencoded ";
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, System.Text.Encoding.GetEncoding("GB2312"));
Html = sr.ReadToEnd();
s.Close();
sr.Close();
}
catch (Exception err)
{
throw new Exception("访问地址出错~~~ ");
}
//去除多余代码,便于分析跟提高效率
int count = Html.Length;
int starIndex = Html.IndexOf("<div id=/"Weather3DBlk/">", 0, count);
int endIndex = Html.IndexOf("<div id=/"SideBar/">", 0);
Html = Html.Substring(starIndex, endIndex - starIndex);
try
{
#region 得到今天的天气
//得到今天的标识跟城市
int firstDayAndCityStartIndex = Html.IndexOf("<h3>", 0);
int firstDayAndCityEndIndex = Html.IndexOf("</h3>", 0);
string FirstDayAndCity = Html.Substring(firstDayAndCityStartIndex + 4, firstDayAndCityEndIndex - firstDayAndCityStartIndex - 4);
//得到今天的日期跟星期
int firstDateStartIndex = Html.IndexOf("<p>", firstDayAndCityEndIndex);
int firstDateEndIndex = Html.IndexOf("</p>", firstDayAndCityEndIndex);
string FirstDate = Html.Substring(firstDateStartIndex + 3, firstDateEndIndex - firstDateStartIndex - 3).Replace(" ", ",");
//得到今天的天气
int firstWeatherStartIndex = Html.IndexOf("<div class=/"Weather_TP/">", firstDateEndIndex);
int firstWeatherEndIndex = Html.IndexOf(" ", firstWeatherStartIndex + 24);
string FirstWeather = Html.Substring(firstWeatherStartIndex + 24, firstWeatherEndIndex - firstWeatherStartIndex - 24);
//得到今天的温度
int firstTemperatureStartIndex = firstWeatherEndIndex + 1;
int firstTemperatureEndIndex = Html.IndexOf("</div>", firstTemperatureStartIndex);
string FirstTemperature = Html.Substring(firstTemperatureStartIndex, firstTemperatureEndIndex - firstTemperatureStartIndex);
int int1 = FirstTemperature.IndexOf("℃", 0);
int int2 = FirstTemperature.IndexOf("~", 0);
int int3 = FirstTemperature.IndexOf("℃", int2);
string FirstMinTemperature = FirstTemperature.Substring(int2 + 1, int3 - int2);
string FirstMaxTemperature = FirstTemperature.Substring(0, int2 - int1 + 2);
//得到今天的风力
int firstWindforceStartIndex = Html.IndexOf("风力:", firstTemperatureEndIndex);
int firstWindforceEndIndex = Html.IndexOf("</div>", firstWindforceStartIndex);
string FirstWindforce = Html.Substring(firstWindforceStartIndex + 3, firstWindforceEndIndex - firstWindforceStartIndex - 3);
if (FirstWindforce.Contains("至"))
{
}
else if (FirstWindforce.Contains("<")) //判断风力是否含有"<"或"≤"字样将,如果有的话,将其替换为2-
{
string strWindforce = FirstWindforce.Substring(1, FirstWindforce.Length - 2);
int minWindforce = Int32.Parse(strWindforce) - 1;
FirstWindforce = FirstWindforce.Replace("<", minWindforce.ToString() + "-");
}
else if (FirstWindforce.Contains("≤"))
{
string strWindforce = FirstWindforce.Substring(1, FirstWindforce.Length - 2);
int minWindforce = Int32.Parse(strWindforce) - 1;
FirstWindforce = FirstWindforce.Replace("≤", minWindforce.ToString() + "-");
}
#endregion
#region 得到明天的天气
//得到明天的标识跟城市
int secondDayAndCityStartIndex = Html.IndexOf("<h3>", firstWindforceEndIndex);
int secondDayAndCityEndIndex = Html.IndexOf("</h3>", secondDayAndCityStartIndex);
string secondDayAndCity = Html.Substring(secondDayAndCityStartIndex + 4, secondDayAndCityEndIndex - secondDayAndCityStartIndex - 4);
//得到明天的日期跟星期
int secondDateStartIndex = Html.IndexOf("<p>", secondDayAndCityEndIndex);
int secondDateEndIndex = Html.IndexOf("</p>", secondDateStartIndex);
string SecondDate = Html.Substring(secondDateStartIndex + 3, secondDateEndIndex - secondDateStartIndex - 3).Replace(" ", ",");
//得到明天的天气
int secondWeatherStartIndex = Html.IndexOf("<div class=/"Weather_TP/">", secondDateEndIndex);
int secondWeatherEndIndex = Html.IndexOf(" ", secondWeatherStartIndex + 24);
string SecondWeather = Html.Substring(secondWeatherStartIndex + 24, secondWeatherEndIndex - secondWeatherStartIndex - 24);
//得到明天的温度
int secondTemperatureStartIndex = secondWeatherEndIndex + 1;
int secondTemperatureEndIndex = Html.IndexOf("</div>", secondTemperatureStartIndex);
string SecondTemperature = Html.Substring(secondTemperatureStartIndex, secondTemperatureEndIndex - secondTemperatureStartIndex);
int int4 = SecondTemperature.IndexOf("℃", 0);
int int5 = SecondTemperature.IndexOf("~", 0);
int int6 = SecondTemperature.IndexOf("℃", int2);
string SecondMinTemperature = SecondTemperature.Substring(int5 + 1, int6 - int5);
string SecondMaxTemperature = SecondTemperature.Substring(0, int5 - int4 + 2);
//得到明天的风力
int secondWindforceStartIndex = Html.IndexOf("风力:", secondTemperatureEndIndex);
int secondWindforceEndIndex = Html.IndexOf("</div>", secondWindforceStartIndex);
string SecondWindforce = Html.Substring(secondWindforceStartIndex + 3, secondWindforceEndIndex - secondWindforceStartIndex - 3);
if (SecondWindforce.Contains("至"))
{
}
else if (SecondWindforce.Contains("<")) //判断风力是否含有"<"或"≤"字样将,如果有的话,将其替换为2-
{
string strWindforce = SecondWindforce.Substring(1, FirstWindforce.Length - 2);
int minWindforce = Int32.Parse(strWindforce) - 1;
SecondWindforce = SecondWindforce.Replace("<", minWindforce.ToString() + "-");
}
else if (SecondWindforce.Contains("≤"))
{
string strWindforce = SecondWindforce.Substring(1, SecondWindforce.Length - 2);
int minWindforce = Int32.Parse(strWindforce) - 1;
SecondWindforce = SecondWindforce.Replace("≤", minWindforce.ToString() + "-");
}
#endregion
#region 得到后天的天气
//得到后天的标识跟城市
int thirdDayAndCityStartIndex = Html.IndexOf("<h3>", secondWindforceEndIndex);
int thirdDayAndCityEndIndex = Html.IndexOf("</h3>", thirdDayAndCityStartIndex);
string thirdDayAndCity = Html.Substring(thirdDayAndCityStartIndex + 4, thirdDayAndCityEndIndex - thirdDayAndCityStartIndex - 4);
//得到后天的日期跟星期
int thirdDateStartIndex = Html.IndexOf("<p>", thirdDayAndCityEndIndex);
int thirdDateEndIndex = Html.IndexOf("</p>", thirdDateStartIndex);
string ThirdDate = Html.Substring(thirdDateStartIndex + 3, thirdDateEndIndex - thirdDateStartIndex - 3).Replace(" ", ",");
//得到后天的天气
int thirdWeatherStartIndex = Html.IndexOf("<div class=/"Weather_TP/">", thirdDateEndIndex);
int thirdWeatherEndIndex = Html.IndexOf(" ", thirdWeatherStartIndex + 24);
string ThirdWeather = Html.Substring(thirdWeatherStartIndex + 24, thirdWeatherEndIndex - thirdWeatherStartIndex - 24);
//得到后天的温度
int thirdTemperatureStartIndex = thirdWeatherEndIndex + 1;
int thirdTemperatureEndIndex = Html.IndexOf("</div>", thirdTemperatureStartIndex);
string ThirdTemperature = Html.Substring(thirdTemperatureStartIndex, thirdTemperatureEndIndex - thirdTemperatureStartIndex);
int int7 = ThirdTemperature.IndexOf("℃", 0);
int int8 = ThirdTemperature.IndexOf("~", 0);
int int9 = ThirdTemperature.IndexOf("℃", int2);
string ThirdMinTemperature = ThirdTemperature.Substring(int8 + 1, int9 - int8);
string ThirdMaxTemperature = ThirdTemperature.Substring(0, int8 - int7 + 2);
//得到后天的风力
int thirdWindforceStartIndex = Html.IndexOf("风力:", thirdTemperatureEndIndex);
int thirdWindforceEndIndex = Html.IndexOf("</div>", thirdWindforceStartIndex);
string ThirdWindforce = Html.Substring(thirdWindforceStartIndex + 3, thirdWindforceEndIndex - thirdWindforceStartIndex - 3);
if (ThirdWindforce.Contains("至"))
{
}
else if (ThirdWindforce.Contains("<")) //判断风力是否含有"<"或"≤"字样将,如果有的话,将其替换为2-
{
string strWindforce = ThirdWindforce.Substring(1, ThirdWindforce.Length - 2);
int minWindforce = Int32.Parse(strWindforce) - 1;
ThirdWindforce = ThirdWindforce.Replace("<", minWindforce.ToString() + "-");
}
else if (ThirdWindforce.Contains("≤"))
{
string strWindforce = ThirdWindforce.Substring(1, ThirdWindforce.Length - 2);
int minWindforce = Int32.Parse(strWindforce) - 1;
ThirdWindforce = ThirdWindforce.Replace("≤", minWindforce.ToString() + "-");
}
#endregion
al.Add(FirstDayAndCity);
al.Add(FirstDate);
al.Add(FirstWeather);
al.Add(FirstMinTemperature);
al.Add(FirstMaxTemperature);
al.Add(FirstWindforce);
al.Add(secondDayAndCity);
al.Add(SecondDate);
al.Add(SecondWeather);
al.Add(SecondMinTemperature);
al.Add(SecondMaxTemperature);
al.Add(SecondWindforce);
al.Add(thirdDayAndCity);
al.Add(ThirdDate);
al.Add(ThirdWeather);
al.Add(ThirdMinTemperature);
al.Add(ThirdMaxTemperature);
al.Add(ThirdWindforce);
}
catch (Exception err)
{
}
return al;
}