【问题标题】:Get the static text contents of a web page获取网页的静态文本内容
【发布时间】:2009-10-31 19:15:58
【问题描述】:

我的网站中有一个搜索栏,用于搜索网站中包含特定关键字的所有页面。这是通过查询索引服务器目录来实现的。

我的问题如下,假设我搜索“ASP.NET”这个词,我说 3 个页面包含“ASP.NET”的出现。

我想显示找到关键字“ASP.NET”的行(以便用户获得上下文信息)。

【问题讨论】:

    标签: c# asp.net indexing


    【解决方案1】:

    尝试解析文档,找到搜索词的出现,然后提取周围的文本。这可以通过在同一个标​​签中获取所有文本来完成,或者在同一个句子中获取所有文本。您可以使用正则表达式来做到这一点。

    哪种效果最好取决于您的需求和内容的结构。您还可以包含周围的句子,以达到提取文本的最小长度。

    这里有一个例子,试图在这个问题中提取包含“问题”这个词的句子。它绝不是完美的,但它说明了这个概念,应该让你开始:

    using System;
    using System.Net;
    using System.Text.RegularExpressions;
    class Program
    {
        private const string url =
            "http://stackoverflow.com/questions/1655313/get-the-static-text-contents-of-a-web-page";
        private const string keyword = "question";
    
        private const string regexTemplate = ">([^<>]*?{0}[^<>]*?)<";
        static void Main(string[] args)
        {
            WebClient client = new WebClient();
            string html = client.DownloadString(url);
            Regex regex = new Regex(string.Format(regexTemplate,keyword) , RegexOptions.IgnoreCase);
            var matches = regex.Matches(html);
            foreach (Match match in matches)
                Console.WriteLine(match.Groups[1].Value);
        }
    }
    

    【讨论】:

      【解决方案2】:

      使用 System.Xml.Linq 将页面读入 XDocument。使用 linq 查询 XDocument 中的文本,然后返回 XElement 并进一步询问该元素。

      【讨论】:

      • 嗨迈克!谢谢回复。但对不起,我忘了准确地说我使用的是 .net 2.0 并且我没有 LINQ 支持!不使用LINQ有什么办法吗?
      • 如果网页是有效的 XHTML,这将非常有用。否则,尝试将它们读取为 XML 将导致异常。
      • 如果你不会使用 LINQ,那么 XmlDocument 会帮助你。
      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 2019-01-13
      相关资源
      最近更新 更多