架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

搜索
查看: 16497|回复: 2

[WinForm] C#怎样获取百度搜索结果中所有链接地址

[复制链接]
发表于 2015-4-11 21:06:01 | 显示全部楼层 |阅读模式
C#怎样获取百度搜索结果中所有链接的地址?
就是,通过关键词从百度搜索的结果,然后批量导出来网址,怎么做到?

从网上没找到相关的源码、、、




上一篇:TP-LINK 路由器后门,TPLINK 存在一个 Shell 调试后门
下一篇:WinForm 使用 HttpUtility找不到的解决办法
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2015-4-11 21:35:57 | 显示全部楼层
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using System.Web;
  6. using System.Net;
  7. using System.IO;
  8. namespace baiduRobotStrim
  9. {
  10.     struct BaiduEntry
  11.     {
  12.         public string title, brief, link;
  13.     }

  14.     class Program
  15.     {
  16.         static string GetHtml(string keyword)
  17.         {
  18.             string url = @"http://www.baidu.com/";
  19.             string encodedKeyword = HttpUtility.UrlEncode(keyword, Encoding.GetEncoding(936));
  20.             //百度使用codepage 936字符编码来作为查询串,果然专注于中文搜索……
  21.             //更不用说,还很喜欢微软
  22.             //谷歌能正确识别UTF-8编码和codepage这两种情况,不过本身网页在HTTP头里标明是UTF-8的
  23.             //估计谷歌也不讨厌微软(以及微软的专有规范)
  24.             string query = "s?wd=" + encodedKeyword;

  25.             HttpWebRequest req;
  26.             HttpWebResponse response;
  27.             Stream stream;
  28.             req = (HttpWebRequest)WebRequest.Create(url + query);
  29.             response = (HttpWebResponse)req.GetResponse();
  30.             stream = response.GetResponseStream();
  31.             int count = 0;
  32.             byte[] buf = new byte[8192];
  33.             string decodedString = null;
  34.             StringBuilder sb = new StringBuilder();
  35.             try
  36.             {
  37.                 Console.WriteLine("正在读取网页{0}的内容……", url + query);
  38.                 do
  39.                 {
  40.                     count = stream.Read(buf, 0, buf.Length);
  41.                     if (count > 0)
  42.                     {
  43.                         decodedString = Encoding.GetEncoding(936).GetString(buf, 0, count);
  44.                         sb.Append(decodedString);
  45.                     }
  46.                 } while (count > 0);
  47.             }
  48.             catch
  49.             {
  50.                 Console.WriteLine("网络连接失败,请检查网络设置。");
  51.             }
  52.             return sb.ToString();
  53.         }
  54.         static void PrintResult(List<BaiduEntry> entries)
  55.         {
  56.             int count = 0;
  57.             entries.ForEach(delegate(BaiduEntry entry)
  58.             {
  59.                 Console.WriteLine("找到了百度的第{0}条搜索结果:", count += 1);
  60.                 if (entry.link != null)
  61.                 {
  62.                     Console.WriteLine("找到了一条链接:");
  63.                     Console.WriteLine(entry.link);
  64.                 }
  65.                 if (entry.title != null)
  66.                 {
  67.                     Console.WriteLine("标题为:");
  68.                     Console.WriteLine(entry.title);
  69.                 }
  70.                 if (entry.brief != null)
  71.                 {
  72.                     Console.WriteLine("下面是摘要:");
  73.                     Console.WriteLine(entry.brief);
  74.                 }
  75.                 Program.Cut();
  76.             });
  77.         }
  78.         static void simpleOutput()
  79.         {
  80.             string html = "<table><tr><td><font>test</font><a>hello</a><br></td></tr></table>";
  81.             Console.WriteLine(RemoveSomeTags(html));
  82.         }
  83.         static string RemoveVoidTag(string html)
  84.         {
  85.             string[] filter = { "<br>" };
  86.             foreach (string tag in filter)
  87.             {
  88.                 html = html.Replace(tag, "");
  89.             }
  90.             return html;
  91.         }
  92.         static string ReleaseXmlTags(string html)
  93.         {
  94.             string[] filter = { "<a.*?>", "</a>", "<em>", "</em>", "<b>", "</b>", "<font.*?>", "</font>" };
  95.             foreach (string tag in filter)
  96.             {
  97.                 html = Regex.Replace(html, tag, "");
  98.             }
  99.             return html;
  100.         }

  101.         static string RemoveSomeTags(string html)
  102.         {
  103.             html = RemoveVoidTag(html);
  104.             html = ReleaseXmlTags(html);
  105.             return html;
  106.         }
  107.         static void Cut()
  108.         {
  109.             Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  110.         }
  111.         static void MainProc(string input)
  112.         {
  113.             MainProc(input, false);
  114.         }
  115.         static void MainProc(string input, bool tagsForBrief)
  116.         {
  117.             Regex r = new Regex("<table.*?</table>", RegexOptions.IgnoreCase);
  118.             //提取出(<table>,</table>)对,并等待进一步处理。
  119.             Match m = r.Match(input);
  120.             List<string> collection = new List<string>();
  121.             while (m.Success)
  122.             {
  123.                 collection.Add(m.Value);
  124.                 //找出tagname为table的节点并存储到collection变量中
  125.                 m = m.NextMatch();
  126.             }
  127.             List<BaiduEntry> entries = new List<BaiduEntry>();
  128.             collection.ForEach(delegate(string entry)
  129.             {
  130.                 r = new Regex("<td.*?>(.*)</td>", RegexOptions.IgnoreCase);
  131.                 if(r.IsMatch(entry))
  132.                 {//从entry字符串里捕获到的就是百度里存储在每个table标签里的td标签了。
  133.                     //现阶段中,百度页面里有几个table标签是兄弟节点的关系,
  134.                     //第一个table标签是一个广告,剩下的table标签刚好都是搜索结果。
  135.                     //理想状态下input字符串里只有几个由table标签组织的搜索结果项。
  136.                     //理应使用预处理过的字符串来调用本函数
  137.                     m = r.Match(entry);
  138.                     string html = m.Groups[1].Value;//直接使用捕获分组1的值。
  139.                     //html变量里存储着td节点的innerHTML,那里有真正的搜索结果
  140.                     BaiduEntry baidu = new BaiduEntry();
  141.                     r = new Regex("<a.*?href="(.*?)".*?>", RegexOptions.IgnoreCase);
  142.                     if (r.IsMatch(html))
  143.                     {
  144.                         string linkString = r.Match(html).Groups[1].Captures[0].Value;
  145.                         baidu.link = linkString;
  146.                     }
  147.                     r = new Regex("<font.*</font>");
  148.                     //td节点下有一些嵌套了2层的font标签,把这个大的font标签拿下来。
  149.                     html = r.Match(html).Value;//现在html变量里存储着比较浓缩的信息了。

  150.                     r = new Regex("<font.*?>(.*?)</font>");
  151.                     Match contentMatch = r.Match(html);
  152.                     if (contentMatch.Success)
  153.                     {
  154.                         string title = contentMatch.Groups[1].Captures[0].Value;
  155.                         title = RemoveSomeTags(title);
  156.                         baidu.title = title;
  157.                         contentMatch = contentMatch.NextMatch();
  158.                         if (contentMatch.Success)
  159.                         {
  160.                             string brief = contentMatch.Groups[1].Captures[0].Value;
  161.                             int splitIndex = brief.IndexOf("<font");
  162.                             if (splitIndex > -1)
  163.                                 brief = brief.Substring(0, splitIndex);
  164.                             if (!tagsForBrief)
  165.                                 brief = RemoveSomeTags(brief);
  166.                             //如果不需要带有HTML格式的摘要,那么就处理掉HTML标签
  167.                             baidu.brief = brief;
  168.                         }
  169.                     }
  170.                     else
  171.                     {
  172.                         if (html == "") return;
  173.                         Console.WriteLine("怪了,这里没有找到任何结果。");
  174.                         Console.WriteLine("如果百度已经更改了页面的结构那么程序需要重新设计。");
  175.                         Console.WriteLine("Mark:");
  176.                         Console.WriteLine(html);
  177.                         Cut();
  178.                         Cut();
  179.                         Cut();
  180.                     }
  181.                     entries.Add(baidu);
  182.                 }
  183.             });

  184.             PrintResult(entries);
  185.         }
  186.         public static void Main(string[] args)
  187.         {
  188.             Console.WriteLine("请输入一个关键字。");
  189.             string keyword;
  190.             keyword = Console.ReadLine();
  191.             Console.WriteLine("正在从百度上获取结果,请稍等……");
  192.             string input;
  193.             input = GetHtml(keyword);
  194.             Regex r = new Regex("<table.*class="result"[\\s\\S]*</table>", RegexOptions.IgnoreCase);
  195.             input = r.Match(input).Value;
  196.             MainProc(input);
  197.             Console.ReadKey(true);
  198.         }
  199.     }
  200. }
复制代码


码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2015-4-11 21:36:19 | 显示全部楼层
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using System.Collections.Generic;
  5. using System.Net;
  6. using System.IO;

  7. namespace ConsoleDemo
  8. {
  9.     public class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.            
  14.             
  15.             BaiduSearch baidu = new BaiduSearch();
  16.             Console.WriteLine("请输入单词:");
  17.             string word = Console.ReadLine();
  18.             //"腾讯 抄袭";
  19.             //string word = "software";
  20.             string html = baidu.Search(word);
  21.             if (!string.IsNullOrEmpty(html))
  22.             {
  23.                 int count = baidu.GetSearchCount(html);
  24.                 Console.WriteLine(string.Format("word:{0} count:{1}", word, count));
  25.                 if (count > 0)
  26.                 {
  27.                     List<Keyword> keywords = baidu.GetKeywords(html, word);
  28.                     foreach (Keyword item in keywords)
  29.                     {
  30.                         Console.WriteLine(item.Title + " " + item.Link);
  31.                     }
  32.                 }
  33.             }

  34.             Console.ReadLine();
  35.         }
  36.         private void GetBaiduZhiDao(string urlsearch = @"http://www.baidu.com/baidu?word=%E5%B0%8F%E6%B8%B8%E6%88%8F&tn=360se_8_dg&ie=utf-8")
  37.         {
  38.             //匿名方法+Lambda,读取网页文本
  39.             Func<string, string> GetHtmlCode = url =>
  40.             {
  41.                 WebClient client = new WebClient();
  42.                 Stream stream = client.OpenRead(url);
  43.                 StreamReader readerOfStream = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
  44.                 string html = readerOfStream.ReadToEnd();
  45.                 stream.Close();
  46.                 return html;
  47.             };
  48.             string html_code = GetHtmlCode(urlsearch);
  49.             MatchCollection mc = Regex.Matches(html_code, @"(?is)<a[^>]*?href=(""?)(?<url>http[^"" ]+?)\1[^>]*target=""_blank""[^>]*><font size=""3""[^>]*>(?<text>.+?)</a><br[^>]*><font size=(""?)-1\2>");
  50.             StringBuilder builder = new StringBuilder();
  51.             foreach (Match m in mc)
  52.             {
  53.                 builder.AppendLine("text = " + Regex.Replace(m.Groups["text"].Value, "<[^>]*>", string.Empty));
  54.                 builder.AppendLine("url = " + m.Groups["url"].Value);
  55.             }
  56.             Console.WriteLine(builder.ToString());
  57.         }
  58.     }



  59.     class BaiduSearch
  60.     {
  61.         protected string uri = "http://www.baidu.com/s?wd=";
  62.         //protected string uri = "http://www.baidu.com/s?wd=software&pn=10&usm=2"; // 第二页
  63.         protected Encoding queryEncoding = Encoding.GetEncoding("gb2312");
  64.         protected Encoding pageEncoding = Encoding.GetEncoding("gb2312");
  65.         protected string resultPattern = @"(?<=找到相关结果[约]?)[0-9,]*?(?=个)";

  66.         public string Search(string word)
  67.         {
  68.             string html = string.Empty;
  69.             //string uriString = uri + System.Web.HttpUtility.UrlEncode(word, queryEncoding);
  70.             string uriString = uri;
  71.             try
  72.             {
  73.                 html = WebFunc.GetHtml(uriString, pageEncoding);
  74.             }
  75.             catch (Exception ex)
  76.             {
  77.                 Console.WriteLine(ex.Message);
  78.             }

  79.             return html;
  80.         }

  81.         public int GetSearchCount(string html)
  82.         {
  83.             int result = 0;
  84.             string searchcount = string.Empty;

  85.             Regex regex = new Regex(resultPattern);
  86.             Match match = regex.Match(html);

  87.             if (match.Success)
  88.             {
  89.                 searchcount = match.Value;
  90.             }
  91.             else
  92.             {
  93.                 searchcount = "0";
  94.             }

  95.             if (searchcount.IndexOf(",") > 0)
  96.             {
  97.                 searchcount = searchcount.Replace(",", string.Empty);
  98.             }

  99.             int.TryParse(searchcount, out result);

  100.             return result;
  101.         }

  102.         public List<Keyword> GetKeywords(string html, string word)
  103.         {
  104.             List<Keyword> keywords = new List<Keyword>();

  105.             Regex regTable = new Regex(@"(?is)<table[^>]*?id=(['""]?)(\d{1}|10)\1[^>]*>(?><table[^>]*>(?<o>)|</table>(?<-o>)|(?:(?!</?table\b).)*)*(?(o)(?!))</table>", RegexOptions.IgnoreCase);
  106.             //Regex regTable = new Regex(@"(?is)<table[^>]*?id=(['""]?)(\d{2})\1[^>]*>(?><table[^>]*>(?<o>)|</table>(?<-o>)|(?:(?!</?table\b).)*)*(?(o)(?!))</table>", RegexOptions.IgnoreCase);
  107.             Regex regA = new Regex(@"(?is)<a\b[^>]*?href=(['""]?)(?<link>[^'""\s>]+)\1[^>]*>(?<title>.*?)</a>", RegexOptions.IgnoreCase);

  108.             MatchCollection mcTable = regTable.Matches(html);
  109.             foreach (Match mTable in mcTable)
  110.             {
  111.                 if (mTable.Success)
  112.                 {
  113.                     Match mA = regA.Match(mTable.Value);
  114.                     if (mA.Success)
  115.                     {
  116.                         Keyword keyword = new Keyword();
  117.                         keyword.Link = mA.Groups["link"].Value;
  118.                         keyword.Title = mA.Groups["title"].Value;
  119.                         keywords.Add(keyword);
  120.                     }
  121.                 }
  122.             }

  123.             return keywords;
  124.         }
  125.     }

  126.     class Keyword
  127.     {
  128.         public string Title { get; set; }
  129.         public string Link { get; set; }
  130.         //private string title;
  131.         //public string Title { get { return title; } set { title = value; } }
  132.         //private string link;
  133.         //public string Link { get { return link; } set { link = value; } }
  134.     }

  135.     static class WebFunc
  136.     {
  137.         public static string GetHtml(string url)
  138.         {
  139.             return GetHtml(url, Encoding.UTF8);
  140.         }

  141.         public static string GetHtml(string url, Encoding encoding)
  142.         {
  143.             WebRequest request;
  144.             request = WebRequest.Create(url);
  145.             request.Credentials = CredentialCache.DefaultCredentials;
  146.             WebResponse response;
  147.             response = request.GetResponse();
  148.             return new StreamReader(response.GetResponseStream(), encoding).ReadToEnd();
  149.         }
  150.     }
  151. }
复制代码


码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2025-7-2 05:03

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表