node.js - nightmare.js 试图点击基于 anchor 文本的链接

标签 node.js nightmare

我正在尝试使用 Nightmare ,在 Node js 中基于链接 anchor 文本内的文本单击链接。

这是一些示例代码:

var Nightmare = require('nightmare');
var nightmare = Nightmare({show: true})

    nightmare
    .goto('https://www.wikipedia.org/')
    .inject('js', 'C:/users/myname/desktop/nodejs/node_modules/jquery/dist/jquery.js')
    .wait(500)
var selector = 'a';
nightmare
  .evaluate(function (selector) {
    // now we're executing inside the browser scope.
    return document.querySelector(selector).innerText;
   }, selector) // <-- that's how you pass parameters from Node scope to browser scope
  .end()
  .then(function(result) {
   console.log(result)
  })

我真的不清楚为什么所有标签的内部文本都没有返回?我想我也许可以在 .evalution 方法中做一个 if 语句,这样它就会将要点击的链接限制为例如“英语”。

知道如何根据链接文本点击链接吗?

最佳答案

据我所知,没有办法仅根据它包含的内容来选择 DOM 元素。你要么需要选择所有的 anchor (就像你现在正在做的那样)并根据 innerText 过滤到你想要的东西。然后直接发出点击事件,或者你可以注入(inject) jQuery 并使用 :contains$.click()发出点击。

此外,如果您想要标签中的所有文本,您可能需要使用 document.querySelectorAll() .

作为获取所有文本的示例:

.evaluate(function (selector) {
  return document.querySelectorAll(selector)
    .map(element => element.innerText);
}, selector)

关于node.js - nightmare.js 试图点击基于 anchor 文本的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962152/

相关文章:

javascript - 如何运行在其他文件中定义的 get 和 post 等应用程序功能

node.js - 如何使用 Passport 验证 Sails JS 应用程序?

javascript - 如何使用 Nightmare 点击此链接?

javascript - Mocha 梦魇 : Uncaught TypeError: Cannot read property 'apply' of undefined

node.js - 单击函数未执行执行 Nightmare.js

javascript - 是否可以使用 flow-type 对简单类型(例如 uri)进行类型检查

node.js - 在 Node js 应用程序中使用 Passport 进行身份验证

node.js - 如何使用 nightmare.js 库混淆 JS 文件

javascript - Nightmarejs .click() 在每个元素上有延迟

javascript - 占位符上的 Node 、表达和请求显示批处理\n