基于百度搜索开放平台的天气查询

注:(不是原创,转别人的,用来学习交流的)
(备注:要引入命名空间
using System.Net;
using System.Text.RegularExpressions;

protected void On_Submit(object sender, EventArgs e)
{
string city = Request.Params["txtcity"].ToString();
string tqyb = "天气预报";
tqyb = HttpUtility.UrlEncode(tqyb, System.Text.Encoding.GetEncoding("gb2312"));
city = HttpUtility.UrlEncode(city, System.Text.Encoding.GetEncoding("gb2312"));
string url = string.Format("http://www.baidu.com/s?bs={0}+{1}f=8&wd={0}+{1}", tqyb, city);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
string html = reader.ReadToEnd();
string pattern = "<\\s*TABLE cellspacing=\"0\" cellpadding=\"0\" class=\"al_wt\">([\\s\\S]*?)<\\s*\\/TABLE\\s*>";
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection item = reg.Matches(html);
foreach (Match m in item)
{
html = m.Value;
}
Div_html.InnerHtml = html;
}

当city为空时,查询是你所在城市的天气,你所在城市计算方法应该是根据你的机子的IP来算的, 百度搜索用的是GB2312编码,所以利用HttpUtility.UrlEncode要做一个简单转换。

代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>天气预报</title>
<style type="text/css">
.al_wt
{
margin-top: 5px;
}
.al_wt td
{
font-size: 14px;
line-height: 22px;
text-align: center;
vertical-align: top;
}
.al_wt td img
{
margin: 5px 0;
width: 48px;
height: 48px;
border: none;
}
.al_wt td img.al_il
{
margin-right: 10px;
}
.al_wt td span
{
font-size: 13px;
}
.al_wt td div
{
text-align: center;
padding: 0 5px;
white-space: nowrap;
}
.al_wt .altime_special
{
white-space: nowrap;
}
.al_wt .altemp_special
{
font-size: 15px;
white-space: nowrap;
}
.al_wt .altd_normal strong
{
font-weight: normal;
font-size: 14px;
}
.al_wt .altd_normal .altime_special, .al_wt .altd_normal .altemp_special
{
white-space: normal;
}
.al_wt td.al_tr
{
padding-right: 20px;
}
.al_wt td.al_tl
{
padding-left: 20px;
border-left: 1px solid #e2e9fc;
}
.al_wlink
{
font-size: 12px;
color: #666;
padding: 5px 0;
line-height: 20px;
}
.al_wlink a
{
color: #77c;
margin: 0 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
城市:
<input type="text" id="txtcity" runat="server" />
<input type="button" runat="server" id="Submit" value="查 询" onserverclick="On_Submit" />
</div>
<div id="Div_html" runat="server">
</div>
</form>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值