【问题标题】:Parsing images out of a list using HtmlAgilityPack使用 HtmlAgilityPack 从列表中解析图像
【发布时间】:2012-12-13 08:40:23
【问题描述】:

有一个这样的html页面

<li class="liclass">
some html
<a href="blabla" class="first aclass">
some other html
</li>
<li class="liclass">
some html
<a href="blabla" class="first aclass">
some other html
</li>
<li class="liclass">
some html
<a href="blabla" class="first aclass">
some other html
</li>
...

我想从 lis 中获取所有 href,但是这样我仍然可以获取 li 和 a 标签之间的关系。 所以首先 li 转到第一个标签,第二个到第二个等等..

我有这段代码,但它总是返回相同的 a href 上下文:

    foreach (var node in docu.DocumentNode.SelectNodes("//li[@class='liclass']"))
 {
    String href = node.SelectNodes("//a[@class='first aclass']")[0].Attributes["href"].Value
    }

如何改进该代码?

【问题讨论】:

  • 我猜答案与node.SelectNodes("//a[@class='first aclass']")[0].Attributes["href"].Value中的a之前的//有关
  • 您在每个循环中创建一个新字符串。这就是为什么您总是以最后一次出现的搜索结果结束。
  • 以及如何防止这种情况发生?通常我每个 li 有 1 个 a,我只想要文档当前解析的 li 中的 href
  • 见下面@COLD-TOLD 的回答。他在循环之前声明了字符串。

标签: c# parsing html-agility-pack


【解决方案1】:

你可能想添加所有的 href

 string href="";
 foreach (var node in docu.DocumentNode.SelectNodes("//li[@class='liclass']"))
 {
    href+= node.SelectNodes("//a[@class='first aclass']")[0].Attributes["href"].Value+",";

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 2016-11-20
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多