根据访问用户IP地址自动获取天气预报

根据访问用户IP地址自动获取天气预报,使用了纯真IP数据库,但是由于纯真IP数据库的信息不满足sina查询页面需要的信息,所以整理了下,里面的IP记录还剩下30w左右,原来的是36w的。

=======内容更新===========
已经添加php和asp版本.


完整示例下载点击这里
根据访问用户IP地址自动获取天气预报

上面的代码是未使用ajax来获取,只含有一个ashx文件获取和分析数据用的。
数据库文件太大,压缩文件中只放了一个压缩过的txt文本文件数据。

如何改写为ajax版本的和导入文本文件到acc或者mssql,参考下面的文章

简易天气预报查询【此为ajax版本的,不过没用使用ip数据库】
如何将QQWry.Dat导出为access数据,导入mssql及查询纯真导入后的ip数据【数据库导入的】


返回的数据格式大概如下

+展开
-JavaScript
{
  success:true//只是是否成功
  ,addr:''//访问的用户的IP对应的城市地址
  ,weathers:[//天气数组,从今天到后两天
    {d:'日期',weather:'天气',tmp:'温度',dir:'风向',strong:'风力'}//注意只有当前才有“风向”属性
    ,{d:'日期',weather:'天气',tmp:'温度',strong:'风力'}//明天
    ,{d:'日期',weather:'天气',tmp:'温度',strong:'风力'}//后天
  ]
}


下面就列出weather.ashx中代码【asp.net】

+展开
-C#
<%@ 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] + "[^>]*>|{C} + 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 = "var weather={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("([\\s\\S]+?)", 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;
        }
    }

}


weather.asp【asp版本】
 

+展开
-HTML
<%@ language="vbscript" codepage="936"%>
<%
function RemoveHTML(str)
  dim r:set r=new RegExp:r.ignorecase=true:r.global=true:r.pattern="<[^>]+>"
  RemoveHTML=r.replace(str,"")
  r.pattern="\s*"
  RemoveHTML=r.replace(RemoveHTML,"")
  set r=nothing
end function

function getip()
  dim ip
  ip =Request.ServerVariables("http_x_forwarded_for")
  if ip="" then ip=Request.ServerVariables("remote_addr")
  getip=ip
end function

function wSplit(byval str,istoday)
  dim s1,s2,s3,s4,r,mc
  set r=new RegExp
  r.ignorecase=true
  r.global=true
  if istoday then
    r.pattern="风向:([\s\S]+?)"
    set mc=r.execute(str):s1=mc.item(0).submatches(0)
  else
    r.pattern="天气:([\s\S]+?)

 

"
    set mc=r.execute(str):s2=mc.item(0).submatches(0)
    r.pattern="温度:([\s\S]+?)

 

"
    set mc=r.execute(str):s3=RemoveHTML(mc.item(0).submatches(0))
  end if
  if istoday then
    r.pattern="风力:([\s\S]+?)"
  else
    r.pattern="风力:([\s\S]+?)

 

"
  end if
  set mc=r.execute(str):s4=RemoveHTML(mc.item(0).submatches(0))
  set r=nothing
  wSplit=array(trim(s1),trim(s2),trim(s3),trim(s4))
end function

function nowdate(d)
  nowdate=year(d)&"-"&month(d)&"-"&day(d)
end function

Function BytesToBstr(strBody,CodeBase) 
  dim obj 
  set obj=Server.CreateObject("Adodb.Stream"
  obj.Type=1 
  obj.Mode=3 
  obj.Open 
  obj.Write strBody 
  obj.Position=0 
  obj.Type=2 
  obj.Charset=CodeBase 
  BytesToBstr=obj.ReadText 
  obj.Close 
  set obj=nothing 
End Function 

function getWeather()
  dim ip,json,arr,ipnum,addr,xhr,htmlbody,r,mc,tmparr:json="var weather={success:false};":addr="桂林"
  ip=getip()
  if ip<>"" then
    arr=split(ip,".")
    ipnum=256*256*256*arr(0) + 256*256*arr(1) + 256*arr(2) +arr(3)'转换为数字
    '===========================
    '这里是执行"select 城市名 from 数据库 where ip开始字段>=" & ipNum & " and ip结束字段<=" & ipNum" 语句获取ip对应城市的代码块,地址存在addr中
    '=========================
    if addr<>"" then
      Set xhr=Server.CreateObject("Microsoft.XMLHTTP")
      xhr.open "get","http://php.weather.sina.com.cn/search.php?city="& addr,False
      xhr.send
      htmlbody=bytestobstr(xhr.responseBody,"gb2312")'获取返回的html内容,注意要使用gb2312来获取文本内容
      Set xhr=Nothing
      set r=new RegExp:r.ignorecase=true:r.global=true
      r.pattern=""box-s1-l"">([\s\S])+?

([^>]+)

"
      if r.test(htmlbody) then
        json = "var weather={success:true,addr:'"&addr&"',weathers:[{d:'" &nowdate(now)& "'"
        set mc=r.execute(htmlBody):json=json&",weather:'"&trim(mc.item(0).submatches(1))&"'"
        r.pattern=""w-number"">([\s\S]+?)
"
        set mc=r.execute(htmlBody):json=json&",tmp:'"&trim(RemoveHTML(mc.item(0).submatches(0)))&"'"
        r.pattern=""list-s1"">([\s\S]+?)"
        set mc=r.execute(htmlBody):tmparr=wSplit(mc.item(0).submatches(0),true)
        json=json&",dir:'"&trim(tmparr(0))&"',strong:'"&trim(tmparr(3))&"'}"
        if request("all")="1" then
          r.pattern=""info-area"">([\s\S]+?)

"
          set mc=r.execute(htmlBody)
          dim ubi:ubi=2
          if mc.count<2 then ubi=mc.count
          for i=1 to ubi
            tmparr=wSplit(mc.item(i).submatches(0),false)
            json=json&",{d:'" & nowdate(dateadd("d",i,now)) & "',weather:'" & tmparr(1)&"',tmp:'" & tmparr(2) & "',strong:'" & tmparr(3) & "'}"
          next
        end if
        json=json&"]};"
      end if
      set r=nothing
    end if
  end if
  getWeather=json
end function

response.charset="gb2312"
response.write getWeather()
 %>


weather.php【php版本】

+展开
-HTML

header("content-type","text/html;charset=gb2312");
ini_set('date.timezone','PRC');//设置时间为中国时区
function removeHTML($str)
{
$str=preg_replace("<[^>]+>","",$str);
return $str;
}
function getip(){
  $ip =$_SERVER["http_x_forwarded_for"];
  if(empty($ip)) $ip=$_SERVER["remote_addr"];
  return $ip;
}
function wSplit($str$IsToday){
  $s1 = "";//风向,只有今天才有
  $s2 = "";//天气,非今天
  $s3 = "";//温度,非今天
  $s4 = "";//风力
  if ($IsToday){
   preg_match_all("/风向:([\\s\\S]+?)<\\/li>/i",$str,$m,PREG_SET_ORDER);
    $s1 = $m[0][1];
  }
  else{
    preg_match_all("/天气:([\\s\\S]+?)<\\/p>/i",$str,$m,PREG_SET_ORDER);
    $s2 = $m[0][1];
    preg_match_all("/温度:([\\s\\S]+?)<\\/p>/i",$str,$m,PREG_SET_ORDER);
    $s3 =removeHTML($m[0][1]);
  }
  preg_match_all("/风力:([\\s\\S]+?)<\\/".($IsToday?"li":"p").">/i",$str,$m,PREG_SET_ORDER);
  $s4 = $m[0][1];
  return array( trim($s1),trim($s2),trim($s3),trim($s4) );
}

function getWeather(){
    $ip = getip();
    $json = "var weather={success:false};";
    $addr="桂林";//为了测试,这里直接设置变量内容
    if (!empty($ip)){
       $arr=explode(".",$ip);
       $ipNum = 0; $pow = 256;
       $ipNum=$arr[0]*pow($pow,3)+$arr[1]*pow($pow,2)+$arr[2]*pow($pow,1)+$arr[3];
       /*
       执行Sql语句获取城市地址,并保存到$addr变量中
      "select 城市地址 from 表 where ip结束地址>=" .$ipNum.+ " and ip开始地址<=".$ipNum
     */

      if (!empty($addr)){
        $htmlBody=file_get_contents("http://php.weather.sina.com.cn/search.php?city=".$addr);  
        if(preg_match_all("/([\\s\\S]+?)

([^>]+)<\\/h2>/i",$htmlBody,$m,PREG_SET_ORDER)){
          $json="var weather={success:true,addr:'".$addr."',weathers:[{d:'" . date("Y-m-d"). "',weather:'".trim($m[0][2])."'";
          preg_match_all("/([\\s\\S]+?)<\\/div>/i",$htmlBody,$m,PREG_SET_ORDER);
          $json.=",tmp:'".trim($m[0][1])."'";
          preg_match_all("/([\\s\\S]+?)<\\/ul>/i",$htmlBody,$m,PREG_SET_ORDER);
          $tmp=wSplit($m[0][1],true);
          $json.=",dir:'".$tmp[0]."',strong:'".$tmp[3]."'}";
          if($_GET["all"]=="1"||$_POST["all"]=="1"){
              $darr=getdate();
              preg_match_all("/([\\s\\S]+?)<\\/div>/i",$htmlBody,$m,PREG_SET_ORDER);
          for($i=1;$i<3 && $i$m);$i++){
             $tmp=wSplit($m[i][1],false);
             $json += ",{d:'".date("Y-m-d",mktime(0,0,0,$darr["mon"],$darr["mday"]+$i,$darr["year"]))."',weather:'".$tmp[1]."',tmp:'".$tmp[2]. "',strong:'".$tmp[3]."'}";
           }//end for
         }//end get all weather
         $json.="]};";
      }//end find the city
   }//end get the addr
  }//end get the client ip address
  return $json;
}
echo getWeather();
?>

加支付宝好友偷能量挖...


原创文章,转载请注明出处:根据访问用户IP地址自动获取天气预报

评论(1)Web开发网
阅读(334)喜欢(0)Asp.Net/C#/WCF