如前所述,您需要编写自己的 Load(string url) 函数。我很无聊,以前从未听说过HtmlAgilityPack,所以我模拟了一些你可以使用的东西。它读取 url http://www.w3schools.com/html/html_tables.asp 并找到所有 <table> 节点,然后遍历它们以找到所有 <td> 和 <th> 节点。然后将所有单元格内部文本写入页面
这是aspx页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>HtmlAgilityPack quasi table parser</title>
</head>
<body>
<h1>Number of tables <asp:Literal ID="litNumTables" runat="server" /></h1>
<strong>Each <th> and <td> node of each <table> [table][row][cell]</strong>
<ul>
<asp:Repeater ID="rptTrNodes" Runat="server">
<ItemTemplate>
<li>
<%# Container.DataItem.ToString() %>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</body>
</html>
这里是 C# 代码:
using System;
using System.Linq;
using HtmlAgilityPack;
using System.Net;
using System.Collections.Generic;
namespace WebApplication5
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var html = new HtmlDocument();
html.LoadHtml(new WebClient().DownloadString("http://www.w3schools.com/html/html_tables.asp"));
var root = html.DocumentNode;
var tableNodes = root.Descendants("table");
var items = new List<string>();
foreach(var tbs in tableNodes.Select((tbNodes,i) => new { tbNodes = tbNodes, i = i }))
{
items.Add(string.Format("<h2><table> {0}<h2>", tbs.i));
var trs = tbs.tbNodes.Descendants("tr");
foreach(var tr in trs.Select((trNodes, j) => new { trNodes = trNodes, j = j }))
{
var cellCounter = 0;
foreach(var cell in tr.trNodes.Descendants("th"))
{
items.Add(string.Format("<th> [{0}][{1}][{2}] - {3}", tbs.i, tr.j, cellCounter, cell.InnerText.Trim()));
cellCounter++;
}
foreach (var cell in tr.trNodes.Descendants("td"))
{
items.Add(string.Format("<td> [{0}][{1}][{2}] - {3}", tbs.i, tr.j, cellCounter, cell.InnerText.Trim()));
cellCounter++;
}
}
}
litNumTables.Text = tableNodes.Count().ToString();
rptTrNodes.DataSource = items;
rptTrNodes.DataBind();
}
}
}
这应该是不言自明的,但如果它是您正在寻找的,那么我可以进一步解释。