【问题标题】:trying to use query selector to select a specific child in a html document尝试使用查询选择器选择 html 文档中的特定子项
【发布时间】:2022-01-31 03:05:51
【问题描述】:

我选择的网站看起来大致像这样

<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 用于网络爬虫,并且需要能够按下特定新闻帖子中的链接,例如第二个

【问题讨论】:

  • 应该可以正常工作
  • 你应该使用querySelectorAll。看到这个stackoverflow.com/a/41848760/13460667
  • 这在 Chrome 上对我有用。您是否收到任何类型的错误消息?
  • 这行得通。你是把代码放在 DOM 之后,还是使用defer?
  • @KatharineOsborne 它只是在 chrome 会话中尝试它时返回 null,而在 puppeteer 上它会因为找不到任何东西而停止它

标签: javascript node.js puppeteer


【解决方案1】:

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

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

根据元素在同级兄弟中的位置匹配元素 类型(标签名称)

并忽略不同类型的元素。

// 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>

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

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 2021-12-21
    • 2017-06-21
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多