【问题标题】:How to use HTML Agility pack如何使用 HTML 敏捷包
【发布时间】:2010-10-25 05:21:17
【问题描述】:

如何使用HTML Agility Pack?

我的 XHTML 文档不完全有效。这就是我想使用它的原因。我如何在我的项目中使用它?我的项目是 C#。

【问题讨论】:

  • 这个问题对我很有帮助。
  • 旁注:使用处理 NuGet 的 Visual Studio,您现在可以右键单击“参考”并选择“管理 NuGet 包...”,搜索“HtmlAgilityPack”并单击“安装”。然后使用 using/Import 语句开始使用代码。
  • 关于@patridge 的上述评论:我发现在第一次通过 ankhsvn 从 svn 获取项目时,我需要删除然后重新添加对 HtmlAgilityPack 的引用。
  • 任何研究 HTMLAgilityPack 的人都应该考虑 CsQuery,根据我的经验,它是一个更新的库,具有更现代的界面。例如,第一个答案的整个代码可以在 CsQuery 中总结为var body = CQ.CreateFromFile(filePath)["body"]。
  • @BenjaminGruenbaum:为您的 CsQuery 建议点赞 - 只需几分钟即可完成设置,非常易于使用。

标签: c# html html-agility-pack


【解决方案1】:

首先,将HTMLAgilityPack nuget 包安装到您的项目中。

那么,举个例子:

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

// There are various options, set as needed
htmlDoc.OptionFixNestedTags=true;

// filePath is a path to a file containing the html
htmlDoc.Load(filePath);

// Use:  htmlDoc.LoadHtml(xmlString);  to load from a string (was htmlDoc.LoadXML(xmlString)

// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
{
    // Handle any parse errors as required

}
else
{

    if (htmlDoc.DocumentNode != null)
    {
        HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

        if (bodyNode != null)
        {
            // Do something with bodyNode
        }
    }
}

(注意:此代码仅为示例,不一定是最佳/唯一方法。请勿在您自己的应用程序中盲目使用它。)

HtmlDocument.Load() 方法还接受一个流,该流在与 .NET 框架中其他面向流的类集成时非常有用。而HtmlEntity.DeEntitize() 是另一种正确处理 html 实体的有用方法。 (感谢马修)

HtmlDocument 和HtmlNode 是您最常使用的类。类似于 XML 解析器,它提供了接受 XPath 表达式的 selectSingleNode 和 selectNodes 方法。

注意HtmlDocument.Option?????? 布尔属性。这些控制Load 和LoadXML 方法将如何处理您的HTML/XHTML。

还有一个名为 HtmlAgilityPack.chm 的已编译帮助文件,其中包含每个对象的完整参考。这通常位于解决方案的基本文件夹中。

【讨论】:

  • 还要注意 Load 接受一个 Stream 参数,这在很多情况下都很方便。我将它用于 HTTP 流 (WebResponse.GetResponseStream)。另一个需要注意的好方法是 HtmlEntity.DeEntitize(HTML Agility Pack 的一部分)。在某些情况下需要手动处理实体。
  • 注意:在 Html Agility Pack 的最新测试版(2009 年 10 月 3 日发布的 1.4.0 Beta 2)中,由于依赖于 Sandcastle、DocProject 和 Visual Studio 2008 SDK。
  • SelectSingleNode() 好像前一阵子被删了
  • 不,SelectSingleNode 和 SelectNodes 肯定还在。我觉得它应该是 htmlDoc.ParseErrors.Count() 而不是 .Count 有点有趣
  • @MikeBlandford // 部分是的。它似乎在 HtmlAgailityPack 的 PCL 版本中被删除(或从一开始就不存在)。 nuget.org/packages/HtmlAgilityPack-PCL
【解决方案2】:

我不知道这对你有没有帮助,但我写了几篇介绍基础知识的文章。

下一篇文章已完成 95%,我只需要对我编写的代码的最后几部分进行解释即可。如果你有兴趣,我会尽量记住在发布时在这里发布。

【讨论】:

【解决方案3】:

HtmlAgilityPack 使用 XPath 语法,尽管许多人认为它的文档记录很差,但在此 XPath 文档的帮助下使用它没有任何问题:https://www.w3schools.com/xml/xpath_syntax.asp

解析

<h2>
  <a href="">Jack</a>
</h2>
<ul>
  <li class="tel">
    <a href="">81 75 53 60</a>
  </li>
</ul>
<h2>
  <a href="">Roy</a>
</h2>
<ul>
  <li class="tel">
    <a href="">44 52 16 87</a>
  </li>
</ul>

我这样做了:

string url = "http://website.com";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//h2//a"))
{
  names.Add(node.ChildNodes[0].InnerHtml);
}
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//li[@class='tel']//a"))
{
  phones.Add(node.ChildNodes[0].InnerHtml);
}

【讨论】:

  • 完全正确。它完全依赖于XPath 标准。一个人应该首先学习这个标准,然后一切都会变得容易。
  • 您提供的链接不再可用。这可能是新的:w3schools.com/xsl/xpath_syntax.asp
  • 我在 DocumentNode 对象中也看不到任何 SelectNodes() 函数。改名了吗?
  • 您使用的是什么版本,从哪里下载的?根据htmlagilitypack.codeplex.com/SourceControl/latest#Release/1_4_0/…,HtmlNode 类上应该有一个 SelectNodes 方法。
  • 链接不可用,新链接:www.w3schools.com/xml/xpath_syntax.asp
【解决方案4】:

主要HTMLAgilityPack相关代码如下

using System;
using System.Net;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace GetMetaData
{
    /// <summary>
    /// Summary description for MetaDataWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class MetaDataWebService: System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public MetaData GetMetaData(string url)
        {
            MetaData objMetaData = new MetaData();

            //Get Title
            WebClient client = new WebClient();
            string sourceUrl = client.DownloadString(url);

            objMetaData.PageTitle = Regex.Match(sourceUrl, @
            "\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;

            //Method to get Meta Tags
            objMetaData.MetaDescription = GetMetaDescription(url);
            return objMetaData;
        }

        private string GetMetaDescription(string url)
        {
            string description = string.Empty;

            //Get Meta Tags
            var webGet = new HtmlWeb();
            var document = webGet.Load(url);
            var metaTags = document.DocumentNode.SelectNodes("//meta");

            if (metaTags != null)
            {
                foreach(var tag in metaTags)
                {
                    if (tag.Attributes["name"] != null && tag.Attributes["content"] != null && tag.Attributes["name"].Value.ToLower() == "description")
                    {
                        description = tag.Attributes["content"].Value;
                    }
                }
            } 
            else
            {
                description = string.Empty;
            }
            return description;
        }
    }
}

【讨论】:

  • 网站不再可用
【解决方案5】:
    public string HtmlAgi(string url, string key)
    {

        var Webget = new HtmlWeb();
        var doc = Webget.Load(url);
        HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key));

        if (ourNode != null)
        {


                return ourNode.GetAttributeValue("content", "");

        }
        else
        {
            return "not fount";
        }

    }

【讨论】:

    【解决方案6】:

    入门 - HTML 敏捷包

    // From File
    var doc = new HtmlDocument();
    doc.Load(filePath);
    
    // From String
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    
    // From Web
    var url = "http://html-agility-pack.net/";
    var web = new HtmlWeb();
    var doc = web.Load(url);
    

    【讨论】:

      【解决方案7】:

      试试这个

      string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());
      
      private string ParseHmlBody(string html)
              {
                  string body = string.Empty;
                  try
                  {
                      var htmlDoc = new HtmlDocument();
                      htmlDoc.LoadHtml(html);
                      var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
                      body = htmlBody.OuterHtml;
                  }
                  catch (Exception ex)
                  {
      
                      dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
                  }
                  return body;
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-20
        • 2011-01-26
        • 1970-01-01
        相关资源
        最近更新 更多