简体   繁体   English

PhantomJS的要求无法在浏览器中加载

[英]PhantomJS' require failed to load in browser

Here is my code : 这是我的代码:

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

inside test.js 在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();
});

I got these error when viewed using Chrome. 使用Chrome浏览器时出现这些错误。

Uncaught SyntaxError: Unexpected token ILLEGAL Uncaught SyntaxError:意外的令牌非法
test.js:1 Uncaught ReferenceError: require is not defined test.js:1未捕获的ReferenceError:require未定义

I wanted to load PhantomJS in my html project, so that I can begin to scrape websites. 我想在我的html项目中加载PhantomJS,以便可以开始抓取网站。

PhantomJS is a standalone application/browser that takes a script written in JavaScript and drives a headless browser component. PhantomJS是一个独立的应用程序/浏览器,它采用JavaScript编写脚本并驱动无头浏览器组件。 You can't load that script into a browser and drive either PhantomJS or the browser it is executed in with that script. 您不能将该脚本加载到浏览器中并驱动PhantomJS或使用该脚本执行的浏览器。 It is comparable with node.js in that you can't simply run node.js scripts in the browser. 它可以与node.js媲美,因为您不能简单地在浏览器中运行node.js脚本。 Note that node.js and PhantomJS have different execution environments. 请注意,node.js和PhantomJS具有不同的执行环境。

If you want to trigger a PhantomJS script from a client-browser, you would make an HTTP request from the client browser to your server, where you would call the PhantomJS script through exec() or something similar in your favorite server framework/language, compute the result on the server and send it back to the client. 如果您想从客户端浏览器触发PhantomJS脚本,则可以从客户端浏览器向服务器发出HTTP请求,并在其中通过exec()或您喜欢的服务器框架/语言中的类似方法调用PhantomJS脚本,在服务器上计算结果并将其发送回客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM