今天的一个项目需要使用到天气预报这个小功能,这两天找了许多,都是第三方的,但是经理说被360拦截了 没办法了 只有自己写了。 下面是到sina网上抓取的代码 public string GetWeather(string city) { string weacherhtml = string.Empty; //转换输入参数的编码类型 string mycity = System.Web.HttpUtility.UrlEncode(city, System.Text.UnicodeEncoding.GetEncoding("GB2312")); //初始化新的 WebRequest HttpWebRequest webrt = (HttpWebRequest)WebRequest.Create("http://php.weather.sina.com.cn/search.php?city=" + mycity); HttpWebResponse webrs = (HttpWebResponse)webrt.GetResponse(); //从Internet资源返回数据流 Stream stream = webrs.GetResponseStream(); //读取数据流 StreamReader srm = new StreamReader(stream, System.Text.Encoding.Default); //读取数据 weacherhtml = srm.ReadToEnd(); srm.Close(); stream.Close(); webrs.Close(); //针对不同的网站,请查看HTML源文件 int start = weacherhtml.IndexOf("<!-- box begin-->"); //取的字符位置 int end = weacherhtml.IndexOf("<!-- box end-->"); return weacherhtml.Substring(start + 17, end - start); } 我用纯真IP数据库 匹配地址 城市信息是用xml保存的。