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\">") + 22, 8);
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 = " " + CityName + ":" + oktwos + " " + okthrees + " " + okfours;
}
}
}
catch
{
ok = "暫無城市〖" + CityName + "〗的天氣預報";
}
ok = "<span style=\"color:#FF0000;\">" + ok + "</span>";
return ok;
}
當然,其實也就是一個小偷程式的雛形。我本地採用的是UTF-8編碼,對象頁面是GB2312,所以在頁面尾碼處理上不能用Server.UrlEncode,而只能用HttpUtility.UrlEncode進行文字編碼。如果本地是GB2312,可能就不需要進行編碼處理了,但我沒有測試,只是給大家提供一個思路。。
至於下面的那些,都只是分析取得的字串提取有用的內容而已,網上還有很多相似的代碼,大家可以綜合比較一下,都是WebClient的應用。。。