【问题标题】:nightmare.js trying to click on link based on anchor textnightmare.js 试图点击基于锚文本的链接
【发布时间】:2017-01-31 16:08:53
【问题描述】:

我正在尝试使用噩梦,在节点js中根据链接的锚文本内的文本点击链接。

下面是一些示例代码:

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 语句,这样它就会将要点击的链接限制为“English”。

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

【问题讨论】:

    标签: node.js nightmare


    【解决方案1】:

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

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

    以获取所有文本为例:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      相关资源
      最近更新 更多