Practical Usage

1. Environment Setup

1. Reference Approaches

Two mainstream approaches:

  1. Legacy approach: Manually import HtmlAgilityPack.dll
  2. Recommended approach: Install via NuGet package
Install-Package HtmlAgilityPack
2. Frequently‑used Core Classes
Class NamePurpose
HtmlDocumentHTML document container, responsible for loading HTML source
HtmlWebNetwork request class, fetch webpage HTML directly from URL
HtmlNodeSingle HTML DOM node (div/a/p and other tags)
HtmlNodeCollectionHtmlNode collection for multi‑item query results

2. Two Ways to Load HTML

Both will produce an HtmlDocument object

1: Load Local File / HTML String
  1. Load local HTML file
using HtmlAgilityPack;
using System.Text;

HtmlDocument document = new HtmlDocument();
// Load local file with specified encoding
document.Load("news.htm", Encoding.UTF8);Code language: JavaScript (javascript)
  1. Load HTML text string
string htmlStr = "<html>...</html>";
document.LoadHtml(htmlStr);Code language: HTML, XML (xml)
2: Load Webpage Online
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("https://example.com");Code language: JavaScript (javascript)

3. Node Querying

// 1. Instantiate document object
HtmlDocument document = new HtmlDocument();
// 2. Read local html file
document.Load("news.htm", Encoding.UTF8);
// 3. Get document root node
HtmlNode rootNode = document.DocumentNode;
// 4. Batch‑query nodes with XPath, return node collection
HtmlNodeCollection newsList = rootNode.SelectNodes(
    @"//html/body/div[@class='content']/div/div[@class='left']/div[1]/div[@class='blk12']/div[@class='blk122']/a"
);Code language: JavaScript (javascript)

Key Method Reference

  • SelectSingleNode("XPath"):Get the first matching node, returns HtmlNode
  • SelectNodes("XPath"):Get all matching nodes, returns HtmlNodeCollection
  • Course materials show full absolute paths. In real‑world projects, global relative lookup is preferred to simplify XPath and lower breakage risk when page markup changes:
//div[@class='blk122']/aCode language: JSON / JSON with Comments (json)

4. Traverse & Extract Content Example

if(newsList != null)
{
    foreach(HtmlNode aNode in newsList)
    {
        string title = aNode.InnerText;          // Get text inside tag
        string link  = aNode.GetAttributeValue("href",""); // Read href attribute
    }
}Code language: PHP (php)

5. Quick Reference for Important Properties

  • .InnerText:Plain text inside element
  • .InnerHtml:Inner HTML source including child tags
  • .OuterHtml:Current tag plus its full inner HTML markup
  • GetAttributeValue("AttributeName","DefaultValue"):Safely read tag attributes

Practical Usage

Leave a Reply

Your email address will not be published. Required fields are marked *