根据访问用户IP地址自动获取天气预报,使用了纯真IP数据库,但是由于纯真IP数据库的信息不满足sina查询页面需要的信息,所以整理了下,里面的IP记录还剩下30w左右,原来的是36w的。
{
success:true//指示抓取数据是否成功
,addr:'城市'//访问的用户的IP对应的城市地址
,weathers:[//天气数组,从今天到后两天
{d:'日期',weather:'天气',tmp:'温度',dir:'风向',strong:'风力'}//注意只有今天才有“风向”属性
,{d:'日期',weather:'天气',tmp:'温度',strong:'风力'}//明天
,{d:'日期',weather:'天气',tmp:'温度',strong:'风力'}//后天
]
}
下面就列出weather.ashx中代码
<%@ WebHandler Language="C#" Class="weather" %> using System; using System.Web; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Net; public class weather : IHttpHandler { /// /// 获取客户ip地址 /// /// private string GetIP() { string ip = HttpContext.Current.Request.ServerVariables["http_x_forwarded_for"]; if (!UserCheck.IsNotNull(ip)) ip = HttpContext.Current.Request.ServerVariables["remote_addr"]; return ip; } /// /// 从字符串中获取天气,温度和风力 /// /// 内容字符串 /// 是否为今天 /// private string[] Split(string str, bool IsToday) { string s1 = ""//风向,只有今天才有 , s2 = ""//天气,非今天 , s3 = ""//温度,非今天 , s4 = "";//风力 Regex r; Match m; if (IsToday) { r = new Regex("风向:([//s//S]+?)", RegexOptions.Compiled | RegexOptions.IgnoreCase); m = r.Match(str); s1 = m.Groups[1].Value.Trim(); } else { r = new Regex("天气:([//s//S]+?)
", RegexOptions.Compiled | RegexOptions.IgnoreCase); m = r.Match(str); s2 = m.Groups[1].Value.Trim(); r = new Regex("温度:([//s//S]+?)", RegexOptions.Compiled | RegexOptions.IgnoreCase); m = r.Match(str); s3 = RemoveHTML(m.Groups[1].Value).Trim(); } r = new Regex("风力:([//s//S]+?)" + (IsToday ? "" : ""), RegexOptions.Compiled | RegexOptions.IgnoreCase); m = r.Match(str); s4 = m.Groups[1].Value.Trim(); return new string[] { s1, s2, s3, s4 }; } ///
/// 移除字符串中指定的html标记,如果未传递标记名称则全部移除html标记 /// ///
字符串对象 ///
标记名称 ///
public string RemoveHTML(string str, params string[] Tags) { string Pattern = ""; if (Tags.Length == 0) Pattern = "<[^>]+>"; else { for (int i = 0; i < Tags.Length; i++) { Pattern += "<" + Tags[i] + "[^>]*>|" + Tags[i] + ">|"; } Pattern = Pattern.Substring(0, Pattern.Length - 1); } return Regex.Replace(str, Pattern, "", RegexOptions.IgnoreCase); } public void ProcessRequest(HttpContext context) { string Ip = GetIP(), area = "", json = "var weather={success:false};"; if (Ip != null && !string.IsNullOrEmpty(Ip)) { string[] arr = Ip.Split('.'); double ipNum = 0, pow = 256; ipNum = double.Parse(arr[0]) * Math.Pow(pow, 3) + double.Parse(arr[1]) * Math.Pow(pow, 2) + double.Parse(arr[2]) * pow + double.Parse(arr[3]); //这里这块代码要改成你读数据库获取表的列名信息的代码 DBHelper db = new DBHelper(); object addr = DBHelper.ExecScalar("select 城市名 from 数据库 where ip开始字段>=" + ipNum.ToString() + " and ip结束字段<=" + ipNum.ToString(), db.CN); db.CloseDB(); //=================================== if (addr != null) { try { HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create ("http://php.weather.sina.com.cn/search.php?city=" + addr.ToString()); string htmlBody = ""; using (StreamReader sr = new StreamReader(wr.GetResponse().GetResponseStream(), Encoding.GetEncoding(936))) { htmlBody = sr.ReadToEnd(); } Regex r = new Regex("
([//s//S])+?
([^>]+)
", RegexOptions.IgnoreCase | RegexOptions.Compiled); if (r.IsMatch(htmlBody)) { json = "{success:true,addr:'"+addr.ToString()+"',weathers:[{d:'" + DateTime.Now.ToString("yyyy-MM-dd") + "'"; Match m = r.Match(htmlBody); json += ",weather:'" + m.Groups[2].Value + "'"; r = new Regex("
([//s//S]+?)
", RegexOptions.IgnoreCase | RegexOptions.Compiled); m = r.Match(htmlBody); json += ",tmp:'" + RemoveHTML(m.Groups[1].Value).Trim() + "'"; r = new Regex("
", RegexOptions.IgnoreCase | RegexOptions.Compiled); m = r.Match(htmlBody); string[] tmp = Split(m.Groups[1].Value, true); json += ",dir:'" + tmp[0] + "',strong:'" + tmp[3] + "'}"; if (context.Request.QueryString["all"] == "1"||context.Request.Form["all"] == "1") {//这里是判断是否需要取后连天的数据 r = new Regex("
([//s//S]+?)
", RegexOptions.IgnoreCase | RegexOptions.Compiled); MatchCollection mc = r.Matches(htmlBody); for (int i = 1; i < 3 && i < mc.Count; i++) { tmp = Split(mc[i].Groups[1].Value, false); json += ",{d:'" + DateTime.Now.AddDays(i).ToString("yyyy-MM-dd") + "',weather:'" + tmp[1] + "',tmp:'" + tmp[2] + "',strong:'" + tmp[3] + "'}"; } } json += "]}"; } } catch { } } } context.Response.Write(json); } public bool IsReusable { get { return false; } } }
本文来自http://www.w3dev.cn/article/20090825/automatic-get-weather-report-by-visitor-ip.aspx