Comment utiliser le pack HTML Agility

Comment utiliser le HTML Agility Pack ?

Mon document XHTML n’est pas complètement valide. C’est pourquoi je voulais l’utiliser. Comment l’utiliser dans mon projet? Mon projet est en C #.

Tout d’abord, installez le package nuget HTMLAgilityPack dans votre projet.

Ensuite, à titre d’exemple:

 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(xmlSsortingng); to load from a ssortingng (was htmlDoc.LoadXML(xmlSsortingng) // 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 } } } 

(NB: Ce code n’est qu’un exemple et n’est pas nécessairement l’approche la meilleure / la seule. Ne l’utilisez pas aveuglément dans votre propre application.)

La méthode HtmlDocument.Load() accepte également un stream qui est très utile pour s’intégrer à d’autres classes orientées stream dans le framework .NET. Alors que HtmlEntity.DeEntitize() est une autre méthode utile pour traiter correctement les entités HTML. (merci Matthew)

HtmlDocument et HtmlNode sont les classes que vous utiliserez le plus. Semblable à un parsingur XML, il fournit les méthodes selectSingleNode et selectNodes qui acceptent les expressions XPath.

Faites attention au document HtmlDocument.Option?????? propriétés booléennes. Celles-ci contrôlent comment les méthodes Load et LoadXML traiteront votre HTML / XHTML.

Il existe également un fichier d’aide compilé appelé HtmlAgilityPack.chm qui contient une référence complète pour chacun des objects. Ceci est normalement dans le dossier de base de la solution.

Je ne sais pas si cela vous aidera, mais j’ai écrit quelques articles qui présentent les bases.

  • HtmlAgilityPack Article Series
  • Introduction à la bibliothèque HtmlAgilityPack
  • Extraire facilement des liens d’un extrait de HTML avec HtmlAgilityPack

L’article suivant est complet à 95%, je dois juste écrire des explications sur les dernières parties du code que j’ai écrit. Si vous êtes intéressé, je vais essayer de me rappeler de publier ici lorsque je le publie.

HtmlAgilityPack utilise la syntaxe XPath, et bien que beaucoup affirment qu’il est mal documenté, je n’ai eu aucun problème à l’utiliser avec l’aide de cette documentation XPath: https://www.w3schools.com/xml/xpath_syntax.asp

Pour parsingr

 

Jack

Roy

J’ai fait ça:

 ssortingng 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); } 
  public ssortingng HtmlAgi(ssortingng url, ssortingng key) { var Webget = new HtmlWeb(); var doc = Webget.Load(url); HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(ssortingng.Format("//meta[@name='{0}']", key)); if (ourNode != null) { return ourNode.GetAtsortingbuteValue("content", ""); } else { return "not fount"; } } 

Le code associé à HTMLAgilityPack est le suivant

 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 description for MetaDataWebService ///  [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(ssortingng url) { MetaData objMetaData = new MetaData(); //Get Title WebClient client = new WebClient(); ssortingng sourceUrl = client.DownloadSsortingng(url); objMetaData.PageTitle = Regex.Match(sourceUrl, @ "\]*\>\s*(?[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value; //Method to get Meta Tags objMetaData.MetaDescription = GetMetaDescription(url); return objMetaData; } private ssortingng GetMetaDescription(ssortingng url) { ssortingng description = ssortingng.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.Atsortingbutes["name"] != null && tag.Atsortingbutes["content"] != null && tag.Atsortingbutes["name"].Value.ToLower() == "description") { description = tag.Atsortingbutes["content"].Value; } } } else { description = ssortingng.Empty; } return description; } } } 

Mise en route – HTML Agility Pack

 // From File var doc = new HtmlDocument(); doc.Load(filePath); // From Ssortingng 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);