如何使用HTML Agility Pack?
我的XHTML文档不是完全有效。这就是为什么我要使用它。如何在项目中使用它?我的项目在C#中。
var body = CQ.CreateFromFile(filePath)["body"]。
                如何使用HTML Agility Pack?
我的XHTML文档不是完全有效。这就是为什么我要使用它。如何在项目中使用它?我的项目在C#中。
var body = CQ.CreateFromFile(filePath)["body"]。
                Answers:
首先,将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的已编译帮助文件,该文件对每个对象都有完整的引用。这通常在解决方案的基本文件夹中。
SelectSingleNode() 似乎已被删除
                    我不知道这对您是否有帮助,但是我写了几篇文章介绍了这些基础知识。
下一篇文章完成了95%,我只需要写出我编写的代码的最后几部分的说明。如果您有兴趣,那么我会尽量记得在发布时在此处发布。
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标准。首先应该学习该标准,然后一切都会变得容易。
                    与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;
        }
    }
}
                  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";
        }
    }
              尝试这个
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;
        }