【问题标题】:html parse with HtmlAgilityPack in C#在 C# 中使用 HtmlAgilityPack 解析 html
【发布时间】:2015-10-12 21:32:11
【问题描述】:
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);

我想解析上面给出的页面,但我想获取表格的行信息。我尝试过几个例子,但我无法做到。任何建议

【问题讨论】:

    标签: c# html asp.net parsing html-agility-pack


    【解决方案1】:

    例如,您可以像这样解析行:

    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();
        }
    

    【讨论】:

    • 有什么方法可以纠正土耳其语字符也可以给任何地方 UTF-8 属性吗?
    • //tr/td 在树的根部递归地重新启动。如果您知道tr 直接在table 下方,您可能想要执行.//tr/tdtr/td
    • @SimonMourier 我已在您发表评论后更正了帖子:tr/td 工作正常。
    • 好的,我明白了。还有一个问题,我怎样才能到达 标签以从 href 部分获取链接?
    • 你可以使用这个查询来获取href部分:var links = table.SelectNodes("tr/td").Descendants("a").Select(x=>x.Attributes["href"].Value);
    【解决方案2】:

    这是一个枚举所有表格单元格并将每个单元格的内部文本写入控制台的示例

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2019-01-26
      • 2016-11-20
      相关资源
      最近更新 更多