【问题标题】:How to extract html links from html file in C#?如何从 C# 中的 html 文件中提取 html 链接?
【发布时间】:2010-02-25 17:23:48
【问题描述】:

谁能帮助我解释如何从 C# 中的 HTML 文件中提取 url/链接

【问题讨论】:

标签: c# .net html


【解决方案1】:

Html Agility Pack

HtmlDocument doc = new HtmlDocument(); 
doc.Load("file.htm");  
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) 
{
    HtmlAttribute att = link.Attributes["href"];
    yourList.Add(att.Value)  
}  
doc.Save("file.htm");

【讨论】:

  • 这样做。使用 RegEx 解析 HTML 可能是一项非常繁琐的任务,Html Agility Pack 将为您节省大量时间。
  • 同意,HTML 敏捷包是可行的方法。
  • 为 Html Agility 包加分!
【解决方案2】:

使用 HTMLAgility 包...

    private List<string> ParseLinks(string html)
    {
        var doc = new HtmlDocument(); 
        doc.LoadHtml(html);
        var nodes = doc.DocumentNode.SelectNodes("//a[@href]");
        return nodes == null ? new List<string>() : nodes.ToList().ConvertAll(r => r.Attributes.ToList().ConvertAll(i => i.Value)).SelectMany(j => j).ToList();
    }

它对我有用。

【讨论】:

    【解决方案3】:

    您可以使用 HTQL COM 对象并使用查询来查询页面: :href

    HTQLCOMLib.HtqlControl h = new HTQLCOMLib.HtqlControl();
    string page = "<html><body><a href='test1.html'>test1</a><a href='test2.html'>test2</a> </body></html>";
    h.setSourceData(page, page.Length);
    h.setQuery("<a>: href ");
    for (h.moveFirst(); 0 == h.isEOF(); h.moveNext() )
    {
         MessageBox.Show(h.getValueByIndex(1));
    }
    

    它将显示以下消息:

    test1.html

    test2.html

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 2012-04-04
      • 2011-06-04
      • 1970-01-01
      • 2019-11-16
      • 2012-04-10
      相关资源
      最近更新 更多