【问题标题】:How to get a link's title and href value separately with html agility pack?如何使用 html 敏捷包分别获取链接的标题和 href 值?
【发布时间】:2012-02-20 08:36:10
【问题描述】:

我正在尝试下载一个包含这样的表格的页面

<table id="content-table">
  <tbody>
    <tr>
      <th id="name">Name</th>
      <th id="link">link</th>
    </tr>

    <tr class="tt_row">

      <td class="ttr_name">
       <a title="name_of_the_movie" href="#"><b>name_of_the_movie</b></a>
       <br>
       <span class="pre">message</span>
      </td>

      <td class="td_dl">
        <a href="download_link"><img alt="Download" src="#"></a>
      </td>

    </tr>

    <tr class="tt_row"> .... </tr>
    <tr class="tt_row"> .... </tr>
  </tbody>
</table>

我想从 td class="ttr_name" 中提取 name_of_the_movie 并从 td class="td_dl" 下载链接

这是我用来循环遍历表格行的代码

HtmlAgilityPack.HtmlDocument hDocument = new HtmlAgilityPack.HtmlDocument();
hDocument.LoadHtml(htmlSource);
HtmlNode table = hDocument.DocumentNode.SelectSingleNode("//table");

foreach (var row in table.SelectNodes("//tr"))
{
  HtmlNode nameNode = row.SelectSingleNode("td[0]");
  HtmlNode linkNode = row.SelectSingleNode("td[1]");
}

目前我不知道如何检查 nameNode 和 linkNode 并提取其中的数据

任何帮助将不胜感激

问候

【问题讨论】:

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


    【解决方案1】:

    我现在无法测试它,但它应该是:

        string name= namenode.Element("a").Element("b").InnerText;
        string url= linknode.Element("a").GetAttributeValue("href","unknown");
    

    【讨论】:

    • 我需要通过代码点击链接(href)并获取该链接中的一些数据,问题是如何做到这一点。
    【解决方案2】:
    nameNode.Attributes["title"]
    linkNode.Attributes["href"]
    

    假设你得到了正确的节点。

    【讨论】:

      【解决方案3】:
          public const string UrlExtractor = @"(?: href\s*=)(?:[\s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)(?<url>.*?)(?:[\s>""'])";
      
          public static Match GetMatchRegEx(string text)
          {
              return new Regex(UrlExtractor, RegexOptions.IgnoreCase).Match(text);
          }
      

      以下是提取所有 Href Url 的方法。我在我的一个项目中使用了该正则表达式,您可以对其进行修改以满足您的需求,也可以对其进行重写以匹配标题。我想批量匹配更方便

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-19
        • 2012-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        相关资源
        最近更新 更多