在本章中,我们将看看PhantomJS这四个重要对象.它们如下:<
CookiesEnabled
Cookies
LibraryPath
版本
现在让我们详细讨论这些内容.
它告诉cookie是否启用.如果是,它将返回 true ;否则假.
其语法如下 :
phantom.cookiesEnabled
cookieenabled.js
phantom.addCookie ({ //adding cookie with addcookie property name: 'c1', value: '1', domain: 'localhost' }); console.log("Cookie Enabled value is : "+phantom.cookiesEnabled); phantom.exit();
命令 : phantomjs cookieenabled.js
Cookie Enabled value is : true
它有助于向域添加和设置cookie.它返回一个包含域可用的所有cookie的对象.
其语法如下 :
phantom.cookies;
文件名:phantomcookie.js
phantom.addCookie ({ name: 'c1', value: '1', domain: 'localhost' }); phantom.addCookie ({ name: 'c2', value: '2', domain: 'localhost' }); phantom.addCookie ({ name: 'c3', value: '3', domain: 'localhost' }); console.log(JSON.stringify(phantom.cookies)); phantom.exit();
命令 : phantomjs phantomcookie.js
[{"domain":".localhost","httponly":false,"name":"c3","path":"/","secure":false, " value":"3"},{"domain":".localhost","httponly":false,"name":"c2","path":"/","sec u re":false,"value":"2"},{"domain":".localhost","httponly":false,"name":"c1","pat h ":"/","secure":false,"value":"1"}]
在上面的示例中,我们向localhost域添加了一些cookie.然后我们使用 phantom.cookies 获取它.它通过使用 JSON stringify 方法将JavaScript对象转换为字符串,返回包含所有cookie的对象.您还可以使用 foreach 访问Cookie的名称/值.
PhantomJS libraryPath存储脚本 injectJS 方法使用的路径.
其语法如下 :
phantom.libraryPath
以下是查找版本的示例.
var webPage = require('webpage'); var page = webPage.create(); page.open('http://www.IT屋.com/jquery', function(status) { if (status === "success") { page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js ', function() { if (page.injectJs('do.js')) { // returnTitle is a function loaded from our do.js file - see below return returnTitle(); }); console.log(title); phantom.exit(); } } }); window.returnTitle = function() { return document.title; };
上述程序生成以下输出.
Jquery Tutorial
它给出了正在运行的PhantomJS版本并返回详细信息在一个对象中.例如:{"major":2,"minor":1,"patch":1}
其语法如下 :
phantom.version
以下是查找版本的示例.
var a = phantom.version; console.log(JSON.stringify(a)); console.log(a.major); console.log(a.minor); console.log(a.patch); phantom.exit();
上述程序生成以下输出.
{"major":2,"minor":1,"patch":1} 2 1 1
在上面的例子中,我们使用 console.log 来打印版本.目前,我们正在运行版本2.它返回对象,其中包含上面代码块中显示的详细信息.