---------------------- android培训、java培训、期待与您交流! ----------------------
上篇博客里已经实现了向网络服务器发送Http请求,并成功的将网页内容下载到了本地。那么现在我们的首要任务就是分析下到的网页内容,提取地址信息。
先来看看下载到的网页内容(这里只贴出了主要部分html代码,头部尾部已省略):
<body>
<header class="mis-head">
<article id="head" class="mis-clearfix">
<nav class="nv"><a href="http://www.baidu.com" class="logo"><img src="http://www.baidu.com/img/baidu_jgylogo3.gif" width="117" height="38" border="0" alt="到百度首页"></a><span class="tab"><a href="http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=210000">新闻</a><a href="http://www.baidu.com/s?wd=210000&cl=3">网页</a><a href="http://tieba.baidu.com/f?kw=210000">贴吧</a><a href="http://zhidao.baidu.com/q?ct=17&pn=0&tn=ikaslist&rn=10&word=210000&fr=wwwt">知道</a><a href="http://mp3.baidu.com/m?tn=baidump3&ct=134217728&lm=-1&word=210000">MP3</a><a href="http://image.baidu.com/i?tn=baiduimage&ct=201326592&lm=-1&cl=2&word=210000">图片</a><a href="http://video.baidu.com/v?ct=301989888&rn=20&pn=0&db=0&s=25&word=210000">视频</a><a href="http://map.baidu.com/m?word=210000&fr=ps01000">地图</a><b>邮编</b></span></nav> <form id="mini-fm" name="f" action="s" class="fm"><input name="wd" id="kw" class="i" value="210000" maxlength="100" autocomplete="off"><input type="hidden" name="p" value="mini"><input type="hidden" name="rn" value="20"><span class="btn_wr"><input type="submit" id="su" value="百度一下" class="btn" onmousedown="this.className='btn btn_h'" onmouseout="this.className='btn'"></span>
</form>
</article>
</header>
<section class="mis-body">
<article class="region-data">
<h3><em>210000</em>:江苏省 南京市 </h3>
</article>
<article class="region-data">
<h3><em>210000</em>:江苏省 南京市 雨花台区</h3>
</article>
<article class="region-data">
<h3><em>210000</em>:江苏省 南京市 下关区</h3>
</article>
<article class="region-data">
<h3><em>210000</em>:江苏省 南京市 鼓楼区</h3>
</article>
</section>
各位请仔细看html代码,我们需要的信息在<section></section>标签内,其中只需要得到:
<article class="region-data">
<h3><em>210000</em>:江苏省 南京市 </h3>
</article>
即可。也就是我们实际要提取的值在”<h3><em>210000</em>:“和”</h3>“之间。知道了这些就好办了,只要做字符串匹配操作,就能得到想要的值。具体代码如下:
public Dictionary<string, string> GetMailAddress(string html,string mail)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
int startIndex=html.IndexOf("<h3><em>" + mail + "</em>:", 1700);//为了减少字符匹配的时间,设定一个较大的起始匹配索引值。本例从第1700个字符处开始。
int endIndex=html.IndexOf("</h3>",startIndex);
string address = html.Substring(startIndex + 20, endIndex - startIndex - 20);//"<h3><em>210000</em>:"字符串的长度为20
dic.Add(mail, address);
return dic;
}
代码说明:根据用户传进来的html代码和邮编,返回一个邮编和相应地址信息组成的一个键值对对象。
写个调用代码来试下能否运行成功。代码如下:
void Test()
{
string html=DownLoad("210000");//此为上次文章所写的下载html的方法
Dictionary<string,string> dic=GetMailAddress(html,"210000");
MessageBox.Show(dic["210000"]);
}
运行下代码,看是否能够得到我们想要的值呢???
---------------------- android培训、java培训、期待与您交流! ----------------------