天气预报的公用类

using System.Net;

public static string GetWerther(string CityName)
        
{
            WebClient MyWea 
= new WebClient();
            MyWea.Credentials 
= CredentialCache.DefaultCredentials;
            
string strurl = "http://weather.tq121.com.cn/mapanel/index_new.php?city=" + HttpUtility.UrlEncode(CityName, Encoding.Default) + "";   //欲获取的网页地址
            
//Response.Write(strurl);
            Uri MyUri = new Uri(strurl);
            
//
            
//MyWea.QueryString.Add("city", CityName);
            string ok, okone, oktwos, okthrees, okfours;
            
int oktwo, okthree, okfour;
            
/*WebClient MyWeather = new WebClient();
            MyWeather.Credentials = CredentialCache.DefaultCredentials;
*/

            
try
            
{

                
//ok = MyWea.responseBody;
                byte[] pagedata = MyWea.DownloadData(MyUri);
                
//从资源下载数据并返回字节数组。(加@是因为网址中间有"/"符号)

                
//以下两句每次只要使用一条即可,功能是一样是用来转换字符集,根据获取网站页面的字符编码选择
                
//如果获取网站页面采用的是GB2312,则使用这句
                ok = Encoding.Default.GetString(pagedata);
                
//如果获取网站页面采用的是UTF-8,则使用这句 
                
//string ok = Encoding.UTF8.GetString(pagedata);
                if (ok.IndexOf("<title>天气搜索</title>"> 0 && ok.IndexOf(".tq121.com.cn"> 0)
                
{
                    okone 
= ok.Substring(ok.IndexOf(" <span class=\"big-cn\">"+ 228);
                    
if (okone == "未找到您查的城市")
                    
{
                        ok 
= "未找到〖" + CityName + "〗的天气预报资料\n";
                    }

                    
else
                    
{
                        oktwo 
= ok.IndexOf("<td width=\"160\" align=\"center\" valign=\"top\" class=\"weather\">");
                        
//alert();
                        oktwos = ok.Substring(oktwo + 60, ok.IndexOf("</td>", oktwo + 60- oktwo - 60);
                        okthree 
= ok.IndexOf("<td width=\"160\" align=\"center\" valign=\"top\" class=\"weatheren\">", oktwo + 60);
                        okthrees 
= ok.Substring(okthree + 62, ok.IndexOf("</td>", okthree + 60- okthree - 62);
                        okfour 
= ok.IndexOf("<td width=\"153\" valign=\"top\"><span class=\"big-cn\">", okthree + 60);
                        okfours 
= ok.Substring(okfour + 50, ok.IndexOf("<br>", okfour) - okfour - 50);
                        ok 
= "&nbsp;" + CityName + ":" + oktwos + "&nbsp;" + okthrees + "&nbsp;" + okfours;
                    }

                }

            }

            
catch
            
{
                ok 
= "暂无城市〖" + CityName + "〗的天气预报";
            }

            ok 
= "<span style=\"color:#FF0000;\">" + ok + "</span>";
            
return ok;
        }

当然,其实也就是一个小偷程序的雏形。我本地采用的是UTF-8编码,对象页面是GB2312,所以在页面后缀处理上不能用Server.UrlEncode,而只能用HttpUtility.UrlEncode进行文字编码。如果本地是GB2312,可能就不需要进行编码处理了,但我没有测试,只是给大家提供一个思路。。

至于下面的那些,都只是分析取得的字符串提取有用的内容而已,网上还有很多相似的代码,大家可以综合比较一下,都是WebClient的应用。。。
posted @ 2009-12-18 10:24  .NET钉子户  阅读(326)  评论(0编辑  收藏  举报