【问题标题】:Extracting a table row with a particular attribute,using HTMLAGILITY pack使用 HTMLAGILITY 包提取具有特定属性的表行
【发布时间】:2010-06-06 10:51:15
【问题描述】:

考虑这段代码:

<tr>
                                                <td valign=top class="tim_new"><a href="/stocks/company_info/pricechart.php?sc_did=MI42" class="tim_new">3M India</a></td>
                                                <td class="tim_new" valign=top><a href='/stocks/marketstats/indcomp.php?optex=NSE&indcode=Diversified' class=tim>Diversified</a></td>

我想使用 HTMLAgility 包编写一段代码,它将提取第一行中的链接。

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace WebScraper
{
    class Program
    {
        static void Main(string[] args)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml("http://theurl.com");
            try
            {
                var links = doc.DocumentNode.SelectNodes("//td[@class=\"tim_new\"]");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadKey();
            }

        }
    }
}

当我尝试在 try 块中插入 foreach(var link in links) 语句/循环时,会引发运行时错误。

【问题讨论】:

  • 如果我给你看我的代码,你会笑出声来。尽管如此,请允许我(下一条评论中的代码)
  • a runtime error is thrown 错误信息和堆栈跟踪是什么?

标签: c# html parsing html-agility-pack


【解决方案1】:

代码doc.LoadHtml("http://theurl.com"); 将不起作用。 LoadHtml 的参数应该是包含 HTML 的字符串,而不是 URL。您必须先获取 HTML 文档,然后再尝试解析它。

一旦你加载了文档,对于这个特定的例子,你可以使用这个:

IEnumerable<string> links = doc.DocumentNode
                               .SelectNodes("//a[@class='tim_new']")
                               .Select(n => n.Attributes["href"].Value);

【讨论】:

  • 马克,我想专门用 class="tim_new" 提取链接。您会看到上述html中有很多链接
  • 如果属性中不是href,我可以解析"tim_new"吗?
  • @Soham:我已经更新了我的答案,但请注意,您的问题主要与您加载文档的方式有关,而不是与您解析它的方式有关。
  • 是的,马克,我已经注意到这一点并且我已经更改了代码。谢谢您的帮助。我不确定我的查询是否正确。你能对那部分发表更多评论吗?感谢您的代码。
  • @Sohan:您的 XPath 查询没问题。请注意,它会选择整个 td 元素,而不仅仅是链接。在我回答的查询中,我只选择了href 属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多