Saturday, 8 April 2017

How to run phantom JS in node server?

I want to create a Server using node JS and run phantom JS in it. My purpose is have a server that show simple HTML form for searching and response to user inputs. this is my codes:

var http = require ('http');
var fs = require ('fs');
var phantom = require ('phantom');
var express = require ('express');
var app = express();

function amazonn(searching){
    var url = 'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=' + searching;

    phantom.create().then(page => {
            page.open(url, function(status){
            console.log( 'Opened : ' + url + ' with status ' + status + '\n' );

            var amazonList = page.evaluate (function() {
            var amazonElements = document.querySelectorAll(
                '#resultsCol .a-link-normal h2'
            );

            var amazonData = [];

            for (var i = 0; i < amazonElements.length; i++){
                amazonData.push( amazonElements[i].innerHTML.trim() );
            }

            return amazonData;
            } );

            console.log('Current amazon items are : ');
            console.log('----------------------------');

            for(var j = 0; j < amazonList.length; j++){
                console.log( (j + 1) + ' | ' + amazonList[j] );
            }

        phantom.exit();
    })

    })

}
app.use(bodyParser.urlencoded({
    extended: true
}));

app.get('/',function(req,res) {
     fs.readFile("./static/search.html" , function(err, data) {
            if(err) { console.log(err) }
            else{
                res.writeHead(200 , {"Content-Type" : "text/html"});
                res.write(data);
                res.end();
            }
        })
})

app.post('/',function(req,res) {
    console.log(req.body.a);
    var searching = req.body.a;
    amazonn(searching);
    res.end(amazonData);
})

app.listen(8000);
console.log("server is running on port 8000...");

Note: I'm using this npm: phantom npm

According to the above codes when user search something then server must process it with phantom JS and return amazon products to user.

But it doesn't work correctly. please help me to fix it...



via zerOOne

No comments:

Post a Comment