javascript - 无法使用 PhantomJS 找到模块网页

标签 javascript phantomjs discord

我正在使用 PhantomJS 在网页上搜索单词,我尝试将其设置为:

const phantomjs = require("phantomjs-prebuilt");

if (cmd === `${prefix}check`) {
    let word = (args[0]);
    var page = require('webpage').create();
    page.open('https://discordapp.com/channels/000/000', function(err, data) {
        if (err) throw err;
        if (data.indexOf(word) >= 0) {
            message.reply(word+ ' Found!');
        } else {
            message.reply(word+ ' Not found.');
        }
    });
}

但是我收到以下错误:

(node:3520) UnhandledPromiseRejectionWarning: Error: Cannot find module 'webpage'

这是什么原因造成的?

编辑 我刚刚看到它不适用于 Node JS,是否可以调用单独的 JS 文件并传递 (args[0]);

最佳答案

如果你想从 node.js 使用 PhantomJS,你可以,有几个包,其中之一是 phantom .它支持 Promises 和异步/等待功能:

const phantom = require('phantom');

(async function() {
  const instance = await phantom.create();
  const page = await instance.createPage();
  await page.on('onResourceRequested', function(requestData) {
    console.info('Requesting', requestData.url);
  });

  const status = await page.open('https://stackoverflow.com/');
  const content = await page.property('content');
  console.log(content);

  await instance.exit();
})();

您当然可以从命令行启动 PhantomJS 并将必要的参数传递给它:

phantomjs script.js https://stackoverflow.com

然后在脚本中使用 system.args 接收它们

var system = require('system');
var args = system.args;

if (args.length === 1) {
  console.log('Try to pass some arguments when invoking this script!');
} else {
  args.forEach(function(arg, i) {
    console.log(i + ': ' + arg);
  });
}

请注意,您使用的 page.open 有误,回调函数签名中没有 data var。如果您想获取页面的所有内容,请参阅 page.content变量:

page.open('http://phantomjs.org', function (status) {
  var content = page.content;
  console.log('Content: ' + content);
  phantom.exit();
});

关于javascript - 无法使用 PhantomJS 找到模块网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152263/

相关文章:

菜单栏的javascript错误

angularjs - Karma : Running test with phantomjs ends-up with TypeError, 而 Chrome 成功

scala - 在 Play 框架规范中设置 PhantomJSDriver 上的 Accept-Language

Java Discord Bot - 获取角色成员?

javascript - 如何让我的机器人获取已经从 channel 中的用户发送的随机消息,并在触发自动响应时发送该随机消息

node.js - 需要帮助在我的 Discord 机器人上配置加入消息

javascript - 循环 ForEach 之前等待确认

javascript - 从 p :inputText javascript 获取值文本

javascript - 如何使用ajax获取github中的json文件

javascript - 您将如何循环浏览每个图像并检查 casperjs 脚本中的错误?