怎样使用C获取百度搜索结果,并且解析到目标网址.docx

怎样使用C获取百度搜索结果,并且解析到目标网址.docx

  1. 1、本文档共7页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
怎样使用C获取百度搜索结果,并且解析到目标网址

怎样使用C# 获取百度搜索结果,并且解析到目标网址我们首先应该分析百度的搜索结果,发现百度的搜索结果的格式为:图中标记部分可以知道,百度的搜索结果都是在id=”content_left”的结果中的,每个搜索项目的是以class=”result c-container”作为一项, 每项中的题目又是包含在h3标签中,如下图所示:因此我们有了思路:根据关键字获取到百度搜索结果的整个HTML文本正则匹配到搜索结果容器的HTML正则匹配到搜索结果每一项的HTML取出每项结果中的题目和链接地址直接来干的,看下面的代码:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Web;usingSystem.Net;usingSystem.IO;namespace BaiduSearchTest{struct BaiduEntry{publicstring title, brief, link;}class Program{staticstring GetHtml(string keyword){string url =@/;string encodedKeyword = HttpUtility.UrlEncode(keyword, Encoding.GetEncoding(936));//百度使用codepage 936字符编码来作为查询串,果然专注于中文搜索……//更不用说,还很喜欢微软//谷歌能正确识别UTF-8编码和codepage这两种情况,不过本身网页在HTTP头里标明是UTF-8的//估计谷歌也不讨厌微软(以及微软的专有规范)string query =s?wd=+ encodedKeyword;? HttpWebRequest req; HttpWebResponse response; Stream stream; req =(HttpWebRequest)WebRequest.Create(url + query); response =(HttpWebResponse)req.GetResponse(); stream = response.GetResponseStream();int count =0;byte[] buf =newbyte[8192];string decodedString =null; StringBuilder sb =new StringBuilder();try{ Console.WriteLine(正在读取网页{0}的内容……, url + query);do{ count = stream.Read(buf, 0, buf.Length);if(count 0){ decodedString = Encoding.GetEncoding(utf-8).GetString(buf, 0, count); sb.Append(decodedString);}}while(count 0);}catch{ Console.WriteLine(网络连接失败,请检查网络设置。);}return sb.ToString();}staticvoid PrintResult(ListBaiduEntry entries){int count =0; entries.ForEach(delegate(BaiduEntry entry){ Console.WriteLine(找到了百度的第{0}条搜索结果:, count +=1);if(entry.link!=null){ Console.WriteLine(找到了一条链接:); Console.WriteLine(entry.link);}if(entry.title!=null){ Console.WriteLine(标题为:); Console.WriteLine(entry.title);}if(entry.brief!=null){

文档评论(0)

dashewan + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档