【问题标题】:Parse inner HTML解析内部 HTML
【发布时间】:2011-10-13 21:57:18
【问题描述】:

这就是我要解析的内容

<div class="photoBox pB-ms">
<a href="/user_details?userid=ePDZ9HuMGWR7vs3kLfj3Gg">
<img width="100" height="100" alt="Photo of Debbie K." src="http://s3-media2.px.yelpcdn.com/photo/xZab5rpdueTCJJuUiBlauA/ms.jpg">
</a>
</div>

我正在使用以下 XPath 来查找它

HtmlNodeCollection bodyNode = htmlDoc.DocumentNode.SelectNodes("//div[@class='photoBox pB-ms']");

这很好,返回,s me all div,s with photobox class

但是当我想使用 ahref 时

HtmlNodeCollection bodyNode = htmlDoc.DocumentNode.SelectNodes("//div[@class='photoBox pB-ms'//a href]");

我收到错误无效令牌。

我也尝试过使用查询

   var lowestreview =
  from main in htmlDoc.DocumentNode.SelectNodes("//div[@class='photoBox pB-ms']") 
   from rating in main.SelectNodes("//a href")
  select new { Main=main.Attributes[0].Value,AHref = rating.ToString() };

谁能告诉我如何编写 XPath 或查询来获得这个 AHref

【问题讨论】:

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


    【解决方案1】:

    这可行(已测试):

    HtmlNodeCollection bodyNodes = htmlDoc.DocumentNode
                                          .SelectNodes("//div[@class='photoBox pB-ms']/a[@href]");
    foreach(var node in bodyNodes)
    {
        string href = node.Attributes["href"].Value;
    }
    

    问题是您混淆了属性和元素选择器。此外,您还不清楚您是否真的打算查询集合

    上面的 XPath 选择器将选择所有具有 href 属性的 a 元素,这些元素是具有 'photoBox pB-ms' 类的 div 元素的子节点。然后您可以迭代这个集合并获取每个元素的href 属性值。

    HtmlAgilityPack 现在也支持 Linq(自 1.4 起),因此只需获取特定的属性值就可以更容易(imo),如下所示:

    string hrefValue = htmlDoc.DocumentNode
                              .Descendants("div")
                              .Where(x => x.Attributes["class"].Value == "photoBox pB-ms")
                              .Select(x => x.Element("a").Attributes["href"].Value)
                              .FirstOrDefault();
    

    【讨论】:

      【解决方案2】:

      你可以使用HTMLAgilePack代替XML解析

      HtmlDocument doc = new HtmlDocument();
      doc.LoadHtml([HTML Text]);
      foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
      {
          HtmlAttribute att = link["href"];
          // att.Value
      }
      

      【讨论】:

      • 什么?然而,他正在错误地使用 HTML Agility Pack...。
      • @Jeff:你能告诉我有什么问题吗?
      • 别误会,你的代码没问题。只是您在暗示他正在使用 XML 解析器。但他实际上是在使用 HTML Agility Pack。他的 XPath 不正确,仅此而已。
      猜你喜欢
      • 2016-05-28
      • 2014-07-26
      • 1970-01-01
      • 2015-09-17
      • 2014-02-05
      • 1970-01-01
      • 2013-07-07
      • 2013-07-03
      • 1970-01-01
      相关资源
      最近更新 更多