【问题标题】:To search for strings with in a string (search for all hrefs in HTML source)在字符串中搜索字符串(搜索 HTML 源代码中的所有 href)
【发布时间】:2011-06-17 16:18:55
【问题描述】:

我有一个包含整个网页 HTML 的字符串变量。 该网页将包含指向其他网站的链接。我想创建一个所有hrefs的列表(webcrawler like )。 最好的方法是什么? 使用任何扩展功能会有帮助吗?使用正则表达式怎么样?

提前致谢

【问题讨论】:

    标签: c# .net string


    【解决方案1】:

    使用 DOM 解析器(例如 HTML Agility Pack)来解析您的文档并找到所有链接。

    关于如何使用 HTML Agility Pack 有一个很好的问题here。下面是一个简单的示例来帮助您入门:

    string html = "your HTML here";
    
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    
    doc.LoadHtml(html);
    
    var links = doc.DocumentNodes.DescendantNodes()
       .Where(n => n.Name == "a" && n.Attributes.Contains("href")
       .Select(n => n.Attributes["href"].Value);
    

    【讨论】:

    • @Donut :感谢您对 HTML Agility Pack 的启发。我以前从未使用过它。我现在正在探索它。
    【解决方案2】:

    我想你会发现这回答了你对 T 的问题

    http://msdn.microsoft.com/en-us/library/t9e807fx.aspx

    :)

    【讨论】:

      【解决方案3】:

      我会选择正则表达式。

              Regex exp = new Regex(
                  @"{href=}*{>}",
                  RegexOptions.IgnoreCase);
              string InputText; //supply with HTTP
              MatchCollection MatchList = exp.Matches(InputText);
      

      【讨论】:

        【解决方案4】:

        试试这个正则表达式(应该可以):

        var matches = Regex.Matches (html, @"href=""(.+?)""");
        

        您可以浏览匹配项并提取捕获的 URL。

        【讨论】:

          【解决方案5】:

          您是否考虑过使用 HTMLAGILITYPACK? http://htmlagilitypack.codeplex.com/

          有了这个,您可以简单地使用 XPATH 来获取页面上的所有链接并将它们放入一个列表中。

          private List<string> ExtractAllAHrefTags(HtmlDocument htmlSnippet)
          {
              List<string> hrefTags = new List<string>();
          
              foreach (HtmlNode link in htmlSnippet.DocumentNode.SelectNodes("//a[@href]"))
              {
                  HtmlAttribute att = link.Attributes["href"];
                  hrefTags.Add(att.Value);
              }
          
              return hrefTags;
          }
          

          取自这里的另一个帖子 - Get all links on html page?

          【讨论】:

          • 谢谢 ..我之前没有研究过 HTMLAGILITYPACK ..但我现在是
          猜你喜欢
          • 2016-05-06
          • 1970-01-01
          • 1970-01-01
          • 2018-08-20
          • 2011-03-22
          • 2016-11-30
          相关资源
          最近更新 更多