尝试使用查询 select 或 select html 文档中的特定子项

trying to use query selector to select a specific child in a html document

我选择的网站大致如下所示

<div class="start-left">
    ...
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    <!-- want to get this one above -->
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    <div class="news-post">...</div>
    ...
</div>

试过了,但在 firefox 或 chrome

上都不起作用
document.querySelector('.start-left div:nth-child(2)')

这是否可能,或者我是否需要重新考虑我的做法?我正在为网络爬虫使用 puppeteer,需要能够在特定新闻 post 中按 link,例如第二个

nth-child(n) 计算元素的所有子元素,不管元素的类型(标签名称)。如果在您的目标元素之前有其他不同类型的元素 nth-child 将无法找到正确的元素并且可能 return 为空。

但是,选择器 nth-of-type(n)

matches elements based on their position among siblings of the same type (tag name)

并忽略不同类型的元素。

// nth-child(2) returns null because the 2nd element is not a div
var wrongElement = document.querySelector('.start-left div:nth-child(2)');
// nth-of-type(2) filters using the type of element
var correctElement = document.querySelector('.start-left div:nth-of-type(2)');
console.log('div:nth-child(2): ' + wrongElement);
console.log('div:nth-of-type(2): ' + correctElement.outerHTML);
<div class="start-left">
    <p class="news-post">...</p>
    <p class="news-post">Not this</p>
    <div class="news-post">...</div>
    <div class="news-post">This one</div>
    <!-- want to get this one above -->
    <div class="news-post">...</div>        
</div>

您可以通过将前面元素的数量添加到选择器来使用 work-around,例如 nth-child(4),但是,更可靠的解决方案是使用 nth-of-type(2).