代码之家  ›  专栏  ›  技术社区  ›  Crash893

解析HTML代码链接的正则表达式

  •  4
  • Crash893  · 技术社区  · 16 年前

    我正在研究一个方法,该方法接受字符串(HTML代码)并返回一个数组,该数组包含中包含的所有链接。

    我已经看到了一些类似html功能包的选项,但是它似乎比这个项目需要的要复杂一些

    我也对使用正则表达式感兴趣,因为我对它没有太多的经验,我认为这是一个很好的学习机会。

    到目前为止我的代码是

     WebClient client = new WebClient();
                string htmlCode = client.DownloadString(p);
                Regex exp = new Regex(@"http://(www\.)?([^\.]+)\.com", RegexOptions.IgnoreCase);
                string[] test = exp.Split(htmlCode);
    

    但是我没有得到我想要的结果,因为我还在研究正则表达式

    我要找的sudo代码是“

    4 回复  |  直到 8 年前
        1
  •  3
  •   JaredPar    16 年前

    如果你正在寻找一个傻瓜证明解决方案正则表达式不是你的答案。由于html语言的复杂性,它们从根本上是有限的,不能用于从html文件中可靠地解析出链接或其他相关标记。

    相反,您需要使用实际的html dom api来解析链接。

        2
  •  2
  •   Michael Paulukonis    16 年前

    正则表达式不是HTML的最佳选择。

    参见前面的问题:

    相反,您需要的是已经知道如何解析dom的东西;否则,您就是在发明轮子。

        3
  •  2
  •   Robert Venables    16 年前

    其他用户可能会告诉你“不,停下!正则表达式不应与HTML混合!就像是漂白剂和氨水的混合!”这个建议很有智慧,但不是全部。

    事实上,正则表达式在收集常用格式的链接时工作得很好。不过,更好的方法是使用专门的工具来处理这类事情,比如htmlagilitypack。

    如果使用正则表达式,则可能匹配99.9%的链接,但可能会错过罕见的意外角点情况或格式错误的HTML数据。

    下面是一个我组合在一起的函数,它使用htmlagilitypack来满足您的需求:

        private static IEnumerable<string> DocumentLinks(string sourceHtml)
        {
            HtmlDocument sourceDocument = new HtmlDocument();
    
            sourceDocument.LoadHtml(sourceHtml);
    
            return (IEnumerable<string>)sourceDocument.DocumentNode
                .SelectNodes("//a[@href!='#']")
                    .Select(n => n.GetAttributeValue("href",""));
    
        }
    

    此函数创建一个新的htmlagilitypack.htmldocument,将包含html的字符串加载到其中,然后使用xpath查询“//a[@ref!='']“选择页面上所有不指向“”的链接。然后,我使用linq扩展名select将htmlnodecollection转换为一个字符串列表,其中包含链接指向的ref属性的值。

    下面是一个使用示例:

            List<string> links = 
                DocumentLinks((new WebClient())
                    .DownloadString("http://google.com")).ToList();
    
            Debugger.Break();
    

    这应该比正则表达式有效得多。

        4
  •  0
  •   THX-1138    16 年前

    您可以查找任何类似于http/https模式的url的内容。这不是html的证明,但它会让你得到像httpurl一样的东西,这是你所需要的,我怀疑。您可以添加更多sachem和域。
    regex查找类似于url“in”ref属性的内容(不是严格意义上的)。

    class Program {
        static void Main(string[] args) {
            const string pattern = @"href=[""'](?<url>(http|https)://[^/]*?\.(com|org|net|gov))(/.*)?[""']";
            var regex = new Regex(pattern);
            var urls = new string[] { 
                "href='http://company.com'",
                "href=\"https://company.com\"",
                "href='http://company.org'",
                "href='http://company.org/'",
                "href='http://company.org/path'",
            };
    
            foreach (var url in urls) {
                Match match = regex.Match(url);
                if (match.Success) {
                    Console.WriteLine("{0} -> {1}", url, match.Groups["url"].Value);
                }
            }
        }
    }
    

    输出:

    HREF= http://company.com '-gt; http://company.com网站
    href=“https://company.com”-> https://company.com
    HREF= http://company.org “gt”; http://company.org网站
    “=” http://company.org/ “gt”; http://company.org网站
    HREF= http://company.org/path '-gt; http://company.org网站