我的输入是
html
:
<div class="grid--item user-info user-hover">
<div class="user-gravatar48">
<a href="/users/22656/jon-skeet">
<div class="gravatar-wrapper-48"><img src="https://www.gravatar.com/avatar/6d8ebb117e8d83d74ea95fbdd0f87e13?s=96&d=identicon&r=PG" alt="Jon Skeet's user avatar" width="48" height="48" class="bar-sm"></div>
</a>
</div>
<div class="user-details">
<a href="/users/22656/jon-skeet">Jon Skeet</a>
<span class="user-location">Reading, United Kingdom</span>
<div class="-flair">
<span class="reputation-score" title="reputation score 1,440,518" dir="ltr">1.4m</span><span title="873 gold badges" aria-hidden="true"><span class="badge1"></span><span class="badgecount">873</span></span><span class="v-visible-sr">873 gold badges</span><span title="9172 silver badges" aria-hidden="true"><span class="badge2"></span><span class="badgecount">9172</span></span><span class="v-visible-sr">9172 silver badges</span><span title="9224 bronze badges" aria-hidden="true"><span class="badge3"></span><span class="badgecount">9224</span></span><span class="v-visible-sr">9224 bronze badges</span>
</div>
</div>
<div class="user-tags">
<a href="/questions/tagged/c%23">c#</a>, <a href="/questions/tagged/java">java</a>, <a href="/questions/tagged/.net">.net</a>
</div>
</div>
我对前两个
span
元素感兴趣,它们是 div
与 class="user-details"
的直接后代。
让我们看看您的 HTML。我已经重新格式化了它,以便我们可以看到相关部分的结构:
<div class="user-details">
<a href="/users/22656/jon-skeet">Jon Skeet</a>
<span class="user-location">Reading, United Kingdom</span>
<div class="-flair">
<span class="reputation-score" title="reputation score 1,440,518" dir="ltr">1.4m</span>
<span title="873 gold badges" aria-hidden="true">
<span class="badge1"></span>
<span class="badgecount">873</span>
</span>
<span class="v-visible-sr">873 gold badges</span>
<span title="9172 silver badges" aria-hidden="true">
<span class="badge2"></span>
<span class="badgecount">9172</span>
</span>
<span class="v-visible-sr">9172 silver badges</span>
<span title="9224 bronze badges" aria-hidden="true">
<span class="badge3"></span>
<span class="badgecount">9224</span>
</span>
<span class="v-visible-sr">9224 bronze badges</span>
</div>
</div>
您说您想要定位
div.user-details
的前两个跨度后代,即 span.user-location
和 span.reputation-score
。 (你还没有说为什么你想这样做,这将是有用的背景信息。)
您尝试使用的选择器是
div.user-details span:nth-child(-n+2)
。选择器的第一部分没问题: div.user-details span
返回 div.user-details
的所有跨度后代(编号 13)。通过添加 :nth-child(-n+2)
,您可以过滤结果以仅包含其父级的第一个或第二个子级(数字 9)的范围。您实际上想要做的是过滤结果以仅包含那些属于 div.user-details 的第一个或第二个后代的跨度,但是没有 :nth-descendant 选择器允许您这样做。
您只需要发明一种不同的方法来定位您想要的元素。你不能只使用他们的类名吗?
.user-location, .reputation-score