【问题标题】:get some links from an HTML string [duplicate]从 HTML 字符串中获取一些链接 [重复]
【发布时间】:2017-01-28 23:57:00
【问题描述】:

我有一些字符串,内容是这样的

<a href="http://example.com/2014/06/22/new-idea-about-life.zip">One</a>
<a href="http://example.com/2014/06/22/new-idea-about-life-rar.rar">Two</a>

我需要这个输出:

http://example.com/2014/06/22/new-idea-about-life.zip
http://example.com/2014/06/22/new-idea-about-life-rar.rar

【问题讨论】:

  • 看看 html 敏捷包。它是一个使处理 html 字符串或文件更容易的库。支持 linq-to-objects 等等。还允许您从标签中提取属性,这是您需要在此处执行的操作。
  • 谢谢。它有帮助吗?我不知道如何使用它

标签: c#


【解决方案1】:

HTML Agility Pack 是一个在 C# 中解析 HTML 的好库。

提取url的一个例子是:

var html = "<a href=\"http://reallife.com/2014/06/22/new-idea-about-life.zip\">New idea about life (zip) (25MB)</a><a href=\"http://reallife.com/2014/06/22/new-idea-about-life-rar.rar\">New idea about life (rar) (23MB)</a>
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var links = new List<string>();
foreach (var link in htmlDoc.DocumentNode.SelectNodes("//a[@href]"))
{
    links.Add(link.GetAttributeValue("href", string.Empty));    
}
// do something with the links inside the links-List

【讨论】:

  • 我写了这个但我得到了这些错误uupload.ir/files/ksa2_untitled.png
  • 你知道怎么解决吗?
  • 你需要通过nuget安装库。你做过吗?如果是,那么您需要参考它。
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多