简体   繁体   中英

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

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.

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

I wanted to load PhantomJS in my html project, so that I can begin to scrape websites.

PhantomJS is a standalone application/browser that takes a script written in JavaScript and drives a headless browser component. You can't load that script into a browser and drive either PhantomJS or the browser it is executed in with that script. It is comparable with node.js in that you can't simply run node.js scripts in the browser. Note that node.js and PhantomJS have different execution environments.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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