【问题标题】:Parse HTML With C# [closed]使用 C# 解析 HTML [关闭]
【发布时间】:2013-12-13 19:00:15
【问题描述】:

我想使用 C# 解析 html 页面。有些 html 页面包含很多 html 标签,这里是其中一个示例:

<span class=text14 id="article_content"><!-- RELEVANTI_ARTICLE_START --><span ></b>The 
     most important component for <a
     class=bluelink href="http://www.ynetnews.com/articles/0,7340,L-
     3284752,00.html%20"' onmouseover='this.href=unescape(this.href)' 
     target=_blank>Israel</a>'s
     security is its special relations with the American administration, and especially with its generous purse. When the Netanyahu government launches a great outcry against the <a  ...

但我只想获取由&lt;span class=text14 id="article_content"&gt; 标记包装的内容。 起初我考虑过使用 preg match,但后来意识到它根本没有效率。 我后来读到了 Html Agility PackFizzlerEx - 我想知道是否可以使用这些工具获取由我提到的特定标签包裹的文本,如果有人能告诉我这项任务的执行速度有多快,我将不胜感激。

【问题讨论】:

  • 请搜索并查看 HtmlAgilityPack 的示例。 “多快” - 我相信解析将是 O(length_of_html) 并且查找速度将取决于您的实际搜索条件,但如果您只需要通过 id 进行搜索,则可能是 O(1)
  • 首先,感谢您的回答,但是“查找速度将取决于您的实际搜索条件”是什么意思? ,你在说什么标准?
  • 您的示例元素是“具有类和 ID 的跨度” - 目前尚不清楚您选择该特定元素的标准是什么。很可能只需 id 就足够了,因为它在每个文档中都是唯一的 - 所以 O(1) 除非 HtmlAgilityPack 不优化该搜索。
  • 使用 HtmlAgilityPack 在 DOM 中移动是使用 XPath,所以它非常简单和容易,如果您知道页面的结构,您只需几个命令即可完成。虽然不确定速度。从来不需要测试它。

标签: c# html windows-phone html-agility-pack


【解决方案1】:

使用Html Agility Pack 非常简单:

var markup = @"<span class=text14 id=""article_content""><!-- RELEVANTI_ARTICLE_START --><span ></b>The most important component for <a class=bluelink href=""http://www.ynetnews.com/articles/0,7340,L-3284752,00.html%20""' onmouseover='this.href=unescape(this.href)' target=_blank>Israel</a>'s security is its special relations with the American administration, and especially with its generous purse. When the Netanyahu government launches a great outcry against the</span>";

var doc = new HtmlDocument();
doc.LoadHtml(markup);

var content = doc.GetElementbyId("article_content").InnerText;

Console.WriteLine(content);

【讨论】:

  • 感谢您的回答,您定义的标记只是我要解析的页面的示例,但它仍然很有帮助。再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-22
  • 2016-03-23
  • 2010-09-19
相关资源
最近更新 更多