我正在尝试使用 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/