基于百度搜索开放平台的天气查询
思路: 利用百度搜索開放平臺,簡單分析百度搜索URL參數(shù),請求查詢頁面,再利用正則表達(dá)式,提取相關(guān)內(nèi)容實(shí)現(xiàn)。
效果如下:
protectedvoidOn_Submit(objectsender,EventArgse)
{
stringcity=Request.Params["txtcity"].ToString();
stringtqyb="天氣預(yù)報(bào)";
tqyb=HttpUtility.UrlEncode(tqyb,System.Text.Encoding.GetEncoding("gb2312"));
city=HttpUtility.UrlEncode(city,System.Text.Encoding.GetEncoding("gb2312"));
stringurl=string.Format("http://www.baidu.com/s?bs={0}+{1}f=8&wd={0}+{1}",tqyb,city);
HttpWebRequestrequest=(HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponseresponse=(HttpWebResponse)request.GetResponse();
System.IO.StreamReaderreader=newSystem.IO.StreamReader(response.GetResponseStream(),System.Text.Encoding.GetEncoding("GB2312"));
stringhtml=reader.ReadToEnd();
stringpattern="<\\s*TABLEcellspacing=\"0\"cellpadding=\"0\"class=\"al_wt\">([\\s\\S]*?)<\\s*\\/TABLE\\s*>";
Regexreg=newRegex(pattern,RegexOptions.IgnoreCase);
MatchCollectionitem=reg.Matches(html);
foreach(Matchminitem)
{
html=m.Value;
}
Div_html.InnerHtml=html;
}
當(dāng)city為空時(shí),查詢是你所在城市的天氣,你所在城市計(jì)算方法應(yīng)該是根據(jù)你的機(jī)子的IP來算的,這個(gè)具體百度是怎么做的,還有待研究。
百度搜索用的是GB2312編碼,所以利用HttpUtility.UrlEncode要做一個(gè)簡單轉(zhuǎn)換。
代碼
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>天氣預(yù)報(bào)</title>
<styletype="text/css">
.al_wt
{
margin-top:5px;
}
.al_wttd
{
font-size:14px;
line-height:22px;
text-align:center;
vertical-align:top;
}
.al_wttdimg
{
margin:5px0;
width:48px;
height:48px;
border:none;
}
.al_wttdimg.al_il
{
margin-right:10px;
}
.al_wttdspan
{
font-size:13px;
}
.al_wttddiv
{
text-align:center;
padding:05px;
white-space:nowrap;
}
.al_wt.altime_special
{
white-space:nowrap;
}
.al_wt.altemp_special
{
font-size:15px;
white-space:nowrap;
}
.al_wt.altd_normalstrong
{
font-weight:normal;
font-size:14px;
}
.al_wt.altd_normal.altime_special,.al_wt.altd_normal.altemp_special
{
white-space:normal;
}
.al_wttd.al_tr
{
padding-right:20px;
}
.al_wttd.al_tl
{
padding-left:20px;
border-left:1pxsolid#e2e9fc;
}
.al_wlink
{
font-size:12px;
color:#666;
padding:5px0;
line-height:20px;
}
.al_wlinka
{
color:#77c;
margin:05px;
}
</style>
</head>
<body>
<formid="form1"runat="server">
<div>
城市:
<inputtype="text"id="txtcity"runat="server"/>
<inputtype="button"runat="server"id="Submit"value="查詢"onserverclick="On_Submit"/>
</div>
<divid="Div_html"runat="server">
</div>
</form>
</body>
</html>
總結(jié)
以上是生活随笔為你收集整理的基于百度搜索开放平台的天气查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Markdown 符号公式大全
- 下一篇: android系统里面的mic是哪个ap