使用C#中的HtmlAgilityPack進行html解析

asp.net c# html html-agility-pack parsing

WebClient webClient = new WebClient();
string page = webClient.DownloadString(
    "http://www.deu.edu.tr/DEUWeb/Guncel/v2_index_cron.html");

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);

我想解析上面給出的頁面,但我想得到表格的行信息。我嘗試過幾個例子,但我無法做到這一點。任何建議

一般承認的答案

例如,您可以像這樣解析行:

using System.Net;
using HtmlAgilityPack;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient webClient = new WebClient();
            string page = webClient.DownloadString("http://www.deu.edu.tr/DEUWeb/Guncel/v2_index_cron.html");

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(page);

            HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
            foreach (var cell in table.SelectNodes("tr/td"))
            {
                string someVariable = cell.InnerText;
            }
        }
    }
}

為了完整性,使用LINQ可以輕鬆創建包含所有非空行值的枚舉:

    private static void Main(string[] args)
    {
        WebClient webClient = new WebClient();
        string page = webClient.DownloadString("http://www.deu.edu.tr/DEUWeb/Guncel/v2_index_cron.html");

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(page);

        HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
        var rows = table.SelectNodes("tr/td").Select(cell => cell.InnerText).Where(someVariable => !String.IsNullOrWhiteSpace(someVariable)).ToList();
    }

熱門答案

這是一個枚舉所有表格單元格並將每個內部文本寫入控制台的示例

WebClient webClient = new WebClient();
var page = webClient.DownloadString("http://www.deu.edu.tr/DEUWeb/Guncel/v2_index_cron.html");

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);

foreach (var td in doc.DocumentNode.SelectNodes("//table/tr/td"))
{
    Console.WriteLine(td.InnerText);
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow