HtmlAgilityPack - 正确获取同名的第二个 class

HtmlAgilityPack - get the second class with the same name correctly

我想解析一些 Pikabu.ru 页面,现在我需要获取用户的帖子总数。 例如,这是我自己的个人资料。我需要获得“280”号码。 https://api.asm.skype.com/v1/objects/0-weu-d6-606eeb4b94e49a4ef8971bec5767e1b0/views/imgpsh_fullsize_anim

如你所见,'profile__digital'class的元素有4个,所以我只需要解析第三个

我写了这个:

HtmlNode node = (doc.DocumentNode.Descendants("section").Where(d => d.Attributes["class"].Value.Contains("section_padding_none")).First()); //all is ok
textBox2.Text = node.SelectSingleNode("//span[contains(@class, 'profile__digital')][2]").InnerHtml; //wrong!

但是它抛出ArgumentOutOfRange Exception((。如何正确解析需要的数据? 请帮忙。谢谢。

我认为使用 section_padding_none 作为您的查询的锚点不是一个好的选择。我认为使用 profile__section 会是更好的选择。第一步是将部分缩小到您想要的部分(在本例中,它是三个部分中的第二个)。

//div[contains(@class,'profile__section')][2]
<div class="profile__section">
          <span class="profile__digital hint" aria-label="30&emsp14;685"><b>30К</b> <span><span>рейтинг</span></span></span>
          <span class="profile__digital"><b>2161</b> <span>подписчик</span></span>
          <span class="profile__digital"><b>1940</b> <span>комментариев</span></span>
          <span class="profile__digital"><b>280</b> <span>постов</span></span>
          <span class="profile__digital"><b>103</b> <span>в "горячем"</span></span>
        </div>

该部分使用 span 组织,值以粗体显示。所以 select 具有您想要的值的跨度(第四个)然后是粗体标记。

span[contains(@class,'profile__digital')][4]/b

这可以全部组合成一个 xpath 表达式。

//div[contains(@class,'profile__section')][2]/span[contains(@class,'profile__digital')][4]/b