【问题标题】:PhantomJS' require failed to load in browserPhantomJS 的要求无法在浏览器中加载
【发布时间】:2015-08-11 10:50:48
【问题描述】:

这是我的代码:

<html>
<body>
  <script src="bin/phantomjs"></script>
  <script src="js/test.js"></script>
</body>
</html>

在 test.js 中

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var ua = page.evaluate(function () {
            return document.getElementById('myagent').innerText;
        });
        console.log(ua);
    }
    phantom.exit();
});

使用 Chrome 查看时出现这些错误。

Uncaught SyntaxError: Unexpected token ILLEGAL
test.js:1 Uncaught ReferenceError: require is not defined

我想在我的 html 项目中加载 PhantomJS,这样我就可以开始抓取网站了。

【问题讨论】:

    标签: javascript browser phantomjs


    【解决方案1】:

    PhantomJS 是一个独立的应用程序/浏览器,它采用 JavaScript 编写的脚本并驱动无头浏览器组件。您不能将该脚本加载到浏览器中并驱动 PhantomJS 或使用该脚本执行它的浏览器。它与 node.js 的相似之处在于您不能简单地在浏览器中运行 node.js 脚本。注意 node.js 和 PhantomJS 有不同的执行环境。

    如果您想从客户端浏览器触发 PhantomJS 脚本,您可以从客户端浏览器向您的服务器发出 HTTP 请求,您可以通过 exec() 或您喜欢的服务器框架中的类似名称调用 PhantomJS 脚本/language,在服务器上计算结果并发回给客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-11
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2014-08-17
      • 1970-01-01
      相关资源
      最近更新 更多