PhantomJS API 第一篇

PhantomJS API

  • phantom Object

phantom對象的參數:

phantom.args
phantom.cookiesEnabled
phantom.cookies
phantom.libraryPath
phantom.scriptName
phantom.version

phantom.addCookie({
  'name': 'Added-Cookie-Name',
  'value': 'Added-Cookie-Value',
  'domain': '.google.com'
});

phantom.deleteCookie('Added-Cookie-Name');
phantom.clearCookies();
if (somethingIsWrong) {
  phantom.exit(1);
} else {
  phantom.exit(0);
}

注入類庫

var wasSuccessful = phantom.injectJs('lib/utils.js');

回調函數onError

phantom.onError = function(msg, trace) {
  var msgStack = ['PHANTOM ERROR: ' + msg];
  if (trace && trace.length) {
    msgStack.push('TRACE:');
    trace.forEach(function(t) {
      msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
    });
  }
  console.error(msgStack.join('\n'));
  phantom.exit(1);
};
  • System Module

To start using, you must require a reference to the system module:

var system = require(‘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);
  });
}

env

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

Object.keys(env).forEach(function(key) {
  console.log(key + '=' + env[key]);
});

os

var system = require('system');
var os = system.os;
console.log(os.architecture);  // '32bit'
console.log(os.name);  // 'windows'
console.log(os.version);  // '7'

pid

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

console.log(pid);

platform

var system = require('system');
console.log(system.platform); // 'phantomjs'
  • Child Process Module
var process = require("child_process")
var spawn = process.spawn
var execFile = process.execFile

var child = spawn("ls", ["-lF", "/rooot"])

child.stdout.on("data", function (data) {
  console.log("spawnSTDOUT:", JSON.stringify(data))
})

child.stderr.on("data", function (data) {
  console.log("spawnSTDERR:", JSON.stringify(data))
})

child.on("exit", function (code) {
  console.log("spawnEXIT:", code)
})

//child.kill("SIGKILL")

execFile("ls", ["-lF", "/usr"], null, function (err, stdout, stderr) {
  console.log("execFileSTDOUT:", JSON.stringify(stdout))
  console.log("execFileSTDERR:", JSON.stringify(stderr))
})

spawn

var page  = require('webpage').create();
var spawn = require('child_process').spawn;

page.open('http://google.com', function(status){
  if( status == 'success' ) {
    page.render('/tmp/google-snapshot.jpg');
    spawn('/usr/bin/sensible-browser', 'file:///tmp/google-snapshot.jpg');
  }
  setTimeout(function(){
    phantom.exit();
  },2000);
});
  • Web Server Module

var webserver = require(‘webserver’);

Here is a simple example that always gives the same response regardless of the request:

var webserver = require('webserver');
var server = webserver.create();
var service = server.listen(8080, function(request, response) {
  response.statusCode = 200;
  response.write('<html><body>Hello!</body></html>');
  response.close();
});

If you want to bind to specify address, just use ipaddress:port instead of port.

var webserver = require('webserver');
var server = webserver.create();
var service = server.listen('127.0.0.1:8080', function(request, response) {
  response.statusCode = 200;
  response.write('<html><body>Hello!</body></html>');
  response.close();
});

An optional object opts can be passed between the IP/port and the callback:

var service = server.listen(8080, {
  'keepAlive': true
}, function(request, response) {

});
  • File System Module

var fs = require(‘fs’);

absolute

var fs = require('fs');

// Print the directory from which phantomjs was run:
var cwd = fs.absolute(".");
console.log(cwd);

// The parent directory:
var parent = fs.absolute("../");
console.log(parent);

// Absolute path of a child directory:
var kid = fs.absolute("/below");
console.log(kid);

changeWorkingDirectory

var fs = require('fs');
console.log(fs.workingDirectory); //prints the location where phantomjs is running
fs.changeWorkingDirectory("C:\\");
console.log(fs.workingDirectory); //prints C:/

copyTree

var fs = require('fs');
fs.copyTree("sourceFolder/", "destinationFolder/");
phantom.exit();

copy

var fs = require('fs');
fs.copy("A.txt", "folder/A.txt");

exists

var fs = require('fs');
var path = 'output.txt';

if (!fs.exists(path))
  fs.write(path, 'Hello World', 'w');

phantom.exit();

isAbsolute

var fs = require('fs');
var path = '/Full/Path/To/test.txt';

// isAbsolute(path) returns true if the specified path is an absolute path.
if (fs.isAbsolute(path))
  console.log('"'+path+'" is an absolute path.');
else
  console.log('"'+path+'" is NOT an absolute path.');

phantom.exit();

isDirectory

var fs = require('fs');
var path = "/etc/";
// Get a list all files in directory
var list = fs.list(path);
// Cycle through the list
for(var x = 0; x < list.length; x++){
  // Note: If you didn't end path with a slash, you need to do so here.
    var file = path + list[x];
    if(fs.isDirectory(file)){
        // Do something
    }
}

phantom.exit();

isExecutable

var fs = require('fs');
var path = '/Full/Path/To/exec';

if (fs.isExecutable(path))
  console.log('"'+path+'" is executable.');
else
  console.log('"'+path+'" is NOT executable.');

phantom.exit();

isFile

var fs = require('fs');
var path = "/etc/";
// Get a list all files in directory
var list = fs.list(path);
// Cycle through the list
for(var x = 0; x < list.length; x++){
  // Note: If you didn't end path with a slash, you need to do so here.
    var file = path + list[x];
    if(fs.isFile(file)){
        // Do something
    }
}

phantom.exit();

isLink

var fs = require('fs');
var path = '/Full/Path/To/file';

if (fs.isLink(path))
  console.log('"'+path+'" is a link.');
else
  console.log('"'+path+'" is an absolute path');

phantom.exit();

isReadable

var fs = require('fs');
var path = '/Full/Path/To/file';

if (fs.isReadable(path)) {
  console.log('"'+path+'" is readable.');

  // Open the file
  var otherFile = fs.open(path, {
    mode: 'r' //Read mode
  });
  // Do something with the opened file
}
else
  console.log('"'+path+'" is NOT readable.');

phantom.exit();

isWritable

var fs = require('fs');
var path = '/Full/Path/To/file';

if (fs.isWritable(path)) {
  console.log('"'+path+'" is writable.');

  var content = 'Hello World!';
  fs.write(path, content, 'w');
}
else
  console.log('"'+path+'" is NOT writable.');

phantom.exit();

list

// EXAMPLE: Show a list of files in a specific directory as a fully qualified path:
var fs = require('fs');
var path = "/etc/";
// Get a list all files in directory
var list = fs.list(path);
// Cycle through the list
for(var x = 0; x < list.length; x++){
  // Note: If you didn't end path with a slash, you need to do so here.
    var file = path + list[x];
    if(fs.isFile(file)){
        // Do something
    }
}

phantom.exit();

makeDirectory

var fs = require('fs');
var path = '/Full/Path/To/Test/';

if(fs.makeDirectory(path))
  console.log('"'+path+'" was created.');
else
  console.log('"'+path+'" is NOT created.');

phantom.exit();

makeTree

var fs = require('fs');

var path = '/Full/Path/To/Test/';

if(fs.makeDirectory(path))
  console.log('"'+path+'" was created.');
else
  console.log('"'+path+'" is NOT created.');

phantom.exit();

move

var fs = require('fs');
fs.move("A.txt", "folder/A.txt");

open

var fs = require('fs');

var file = fs.open('/path/to/file', 'r'); //Open Mode. A string made of 'r', 'w', 'a/+', 'b' characters.

var otherFile = fs.open('/path/to/otherFile', {
  mode: 'r' //(see Open Mode above)
});

var yetAnotherFile = fs.open('/path/to/yetAnotherFile', {
  mode: 'w', //(see Open Mode above)
  charset: 'US-ASCII' //An IANA, case insensitive, charset name.
});

file.close();
otherFile.close();
yetAnotherFile.close();

readLink

var fs = require('fs');

var path = '/Full/Path/To/test.txt';

if (fs.isLink(path)) {
  var absolute = fs.readLink(path);
  console.log('The absolute path of "'+path+'" is "'+absolute+'"');
}
else
  console.log('"'+path+'" is an absolute path');

phantom.exit();

read

var fs = require('fs');

var content = fs.read('file.txt');
console.log('read data:', content);

phantom.exit();

removeDirectory

var fs = require('fs');
var toDelete = 'someFolder';

// Test if the folder is empty before deleting it
if(fs.list(toDelete).length === 0)
    fs.removeDirectory(toDelete);

phantom.exit();

removeTree

var fs = require('fs');
var toDelete = 'someFolder';

fs.makeDirectory(toDelete);
fs.touch(toDelete + '/test.txt');

// It will delete the 'someFolder' and the 'test.txt' in it
fs.removeTree(toDelete);

phantom.exit();

remove

var fs = require('fs');
var toDelete = 'someFile.txt';

fs.remove(toDelete);

phantom.exit();

size

var fs = require('fs');
var path = 'someFolder/';

// Go through every element in the folder
fs.list(path).forEach(function(file) {
    file = path + file;
    // Remove every file that are larger than 100 bytes
    if(fs.isFile(file) && fs.size(file) > 100)
        fs.remove(file);
});

phantom.exit();

touch

var fs = require('fs');
var path = 'test.txt';

// Creates an empty file
fs.touch(path);

var text = fs.read(path);

// If the test.txt didn't already exist, this will print an empty string
console.log(text);

phantom.exit();

write

var fs = require('fs');

var path = 'output.txt';
var content = 'Hello World!';
fs.write(path, content, 'w');

phantom.exit();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章