【问题标题】:Parsing HTML using LINQ使用 LINQ 解析 HTML
【发布时间】:2015-02-08 10:24:24
【问题描述】:

我在解析 HTML 文件时需要帮助。我是 C# 和 LINQ 的新手,我尝试的一切都未能成功提取“链接”和“名称 1”

     <tr class="Row">
              <td width="80">
                <div align="left"> <a href="link">details</a>
                </div>
              </td> 
              <td width="152">Name 1</td> 
              <td width="151">Name 2</td> 
              <td width="152">Name 3</td> 
              <td width="151">Name 4</td> 
              <td width="151">Name 5</td> 
              <td width="152">Name 6</td>
      </tr>

      <tr class="Row">
              <td width="80">
                <div align="left"> <a href="link">details</a>
                </div>
              </td> 
              <td width="152">Name 1</td> 
              <td width="151">Name 2</td> 
              <td width="152">Name 3</td> 
              <td width="151">Name 4</td> 
              <td width="151">Name 5</td> 
              <td width="152">Name 6</td>
      </tr>

这是我尝试过的:

                var links = htmlDoc.DocumentNode.Descendants()
                    .Where(n => n.Name == "tr")
                    .Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "Row")
                    .Select(x => x.Descendants()
                    .Where(s => s.Name == "href"));

                foreach (var link in links)
                {
                    Debug.WriteLine(link);
                }

【问题讨论】:

  • 你在使用 Html Agility Pack 吗?
  • 我正在使用 HtmlAgilityPack-PCL
  • 检查答案,如果有不清楚的地方告诉我
  • .Where(s => s.Name == "href") 应该是 .Where(s => s.Name == "a" && a.Attributes["href"]!=空)

标签: c# linq parsing html-parsing


【解决方案1】:
var nodes= htmlDoc.DocumentNode.Descendants()
                    .Where(n => n.Name == "a" || 
(n.Name == "td" && n.Attribute["width"] != null && n.Attribute["width"].Value != "80" && n.Parent.Name == "tr" && n.Parent.Attribute["class"] != null && n.Parent.Attribute["class"].Value = "Row"));


                foreach (var node in nodes)
                {
                    if(node.Attribute["href"] != null)
                    {
                         Debug.WriteLine(node.Attribute["href"].Value);
                    }
                    else
                    {
                         Debug.WriteLine(node.InnerText);
                    }
                }

你需要这样的东西。您正在获取名称为 a 的每个节点或每个宽度不是 80 的 td 节点,并且 tr 父节点具有 class="Row"

【讨论】:

    【解决方案2】:

    您的 linq 不反映 html 的结构。 使用xpath可以简单实现。

     var links = htmlDoc.DocumentElement
        .SelectNodes("//tr[class='Row']/td/div/a")
        .Select(aElem=>aElem.Attributes["href"].Value)
    

    【讨论】:

    • 我不能使用 Xpath,因为我的项目是 Windows Phone 8.1
    猜你喜欢
    • 2019-01-26
    • 2011-06-04
    • 1970-01-01
    • 2015-05-16
    • 2012-08-29
    • 2011-06-13
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多