首先和大侠们介绍一下我做的小系统的要求吧,“根据某个指定的关键词,搜索带有该关键词的网页(1000~2000个),并将其保存下来。提供查询界面,能够快速的根据网页的网址、标题、大小(仅HTML)、图片数量、链接数量等信息进行排序和检索,能够对这些网页离线浏览。”我的设计思路是,输入问题查询,调用private string GetHtmlCode(string url, Encoding encoding)
    {
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
        System.Net.WebResponse response = request.GetResponse();
        System.IO.Stream resStream = response.GetResponseStream();
        System.IO.StreamReader sr = new System.IO.StreamReader(resStream, encoding);
        string html = (sr.ReadToEnd());
        resStream.Close();
        sr.Close();
        return html;
    }获取谷歌搜索。
然后分析谷歌查询内容,将分析得到的URL 和标题插入数据库。相应代码如下
 public string getgoogle(string url,string question)
    {
            string m_url = "";
            string m_html = GetHtmlCode(url,Encoding.UTF8);
            Regex expression = new Regex(@"<h3.*?href=""http://(?<URL>[^""]*)[^>]*>(?<Title>(?:(?!</a>).)+)</a></h3>");//利用正则表达式分析查询到的内容
            Match match = expression.Match(m_html);
            while (match.Success)
            {
                try
                {
                   // m_url = match.Groups[1].Value;
                    string m = match.Groups[1].Value;
                    string title = match.Groups[2].Value + match.Groups[3].Value + match.Groups[4].Value;
                    string myurl = "http://" + m;
                    //downloadHtml(myurl, Encoding.UTF8);//下载网页到本地  
                    string sql = "insert into s_info values('" + question + "','"+myurl+"','"+title+"')";
                    database db = new database();
                    db.ExecuteSql(sql);//将查询的问题,URL,标题插入到数据库    
         
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); };
                match = match.NextMatch();
            
            }
            return "ok";
            
    }下载文件代码:  private void downloadHtml(string url, Encoding encoding)
    {
        string result = GetHtmlCode(url, Encoding.UTF8);
        FileStream fs = new FileStream(@"F:\test\a.html", FileMode.Create, FileAccess.Write);        StreamWriter sw = new StreamWriter(fs,encoding);
        sw.Write(result);
        sw.Flush();
        sw.Close();
    
    }
现在我有几个困惑,希望大侠指点,菜鸟讨论~
1.这个查询界面该怎么做?我的意思是我输入问题之后,一点查询是不是应该显示一些查询的内容呢?还是说等所有的超链接,标题插入数据库以后再显示查询的结果? 我觉得这两种方案都不好(方案一我不会,方案二时间有问题)。
2.就是关于速度问题,我不知道哪一个步骤用了时间,反正将匹配的问题插入的过程很慢。
3.一个小的技术问题,在那个downloadHtml中,那个路径最后的文件名我想让他是url 这个变量值。没搞定,顺便问一下。希望大家踊跃发言哈~!

解决方案 »

  1.   

    这是搜索引擎的抓取功能,爬虫程序,抓取页面可用
    webclient,httpwebrequest等
    webbrower
    通过post提交到baidu获取页面内容
      

  2.   

    需求不明确,感觉跟我上班做的一样,现在我天天分析html....
    无无语了
    天天正则表达式
      

  3.   

    可能是我问的问题太抽象了~问个具体的~
    在那个downloadHtml中,那个路径最后的文件名我想让他是url 这个变量值。什么格式?