using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Net;using System.Text;using System.Text.RegularExpressions;public partial class _tqyb : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { //-- 将此处的页面地址替换为相应的地址就行了,可以登陆 www.cma.gov.cn 查询到相应的城市 string pageUrl = "http://www.cma.gov.cn/tqyb/weatherdetail/57496.html"; //-- 用于存储抓取出来的地点的名称 string dd = string.Empty; //-- 天气状况 string tqgk = string.Empty; //-- 气温 string qw = string.Empty; //-- 风力/风向 string fxfl = string.Empty; if (!IsPostBack) { WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; Byte[] bt = wc.DownloadData(@pageUrl); string result = Encoding.Default.GetString(bt); if (result.Length <= 0) { Response.Write("未找到指定的城市天气信息!"); return; } int pos = result.IndexOf("<div class=\"font01\">3天预报 </div>"); if (pos > 0) result = "未找到该城市的天气预报!"; else { pos = result.IndexOf("<div class=\"font01\">3天预报"); result = result.Substring(pos, result.IndexOf("穿衣指数") - pos); pos = result.IndexOf(" ") + 18; dd = result.Substring(pos, result.IndexOf("</") - pos); pos = result.IndexOf("天气概况"); result = result.Substring(pos, result.IndexOf("<!--<tr>") - pos); pos = result.IndexOf("<td width=\"75\""); result = result.Substring(pos); pos = result.IndexOf(">"); tqgk = result.Substring(pos + 1, result.IndexOf("</td>") - pos - 1); result = result.Substring(result.IndexOf("气 温")); pos = result.IndexOf("cn\">") + 4; qw = result.Substring(pos, result.IndexOf("℃</td>") - pos + 1); result = result.Substring(result.IndexOf("风向/风力</td>")); result = result.Substring(result.IndexOf("<td")); pos = result.IndexOf("cn\">") + 4; fxfl = result.Substring(pos, result.IndexOf("</td") - pos); tqgk = "今日天气:" + tqgk.Replace(" ", ""); qw = qw.Replace(" ", ""); qw = "最高温度:" + qw.Replace("/", " 最低温度:"); fxfl = "风向/风力:" + fxfl.Replace(" ", ""); result = dd + tqgk + " " + qw + " " + fxfl; } Response.Write("document.write(\"" + result + "\");"); Response.End(); } }}
调用时只需要如下即可:
<script language="javascript" type="text/javascript" src="tqyb.aspx"></script>
即可得到纯文字的当日天气预报,自己再要设置什么格式均可。
转载于:https://www.cnblogs.com/zwl12549/archive/2007/12/03/980570.html
