首页 > 解决方案 > Nightmare JS 点击集合中的随机链接

问题描述

我可以使用以下方法单击链接: nightmare.click("#video-title") 但是,它会单击具有该 ID 的第一个元素。当我 document.querySelectorAll('[id=video-title]') 在 Youtube 上进行搜索时,我得到了大约 85 个结果。有没有办法使用 Nightmare JS 随机点击一个?在通话中返回该列表evaluate对我不起作用

.evaluate(() => { return Array.from(document.querySelectorAll('[id=video-title]')) })

.then(videoLinks => {
      nightmare.click(videoLinks[0])
    })

Nightmare 在点击时给出了这个错误: Error: Failed to execute 'querySelector' on 'Document': '[object Object]' is not a valid selector.

标签: javascriptjquerybrowserautomationnightmare

解决方案


像这样的东西应该工作:

.evaluate(() => {

     const list = document.querySelectorAll('[id=video-title]')
     return list[Math.floor(Math.random()*list.length)]

 })

作为回报,它通过 queryselectorAll 为您提供 NodeList 中的随机元素


推荐阅读