来自:莲颂 > 馆藏分类
配色: 字号:
Phantomjs API 中文版(第一版)
2018-03-14 | 阅:  转:  |  分享 
  
PhantomjsAPI中文版CommandLineInterface命令行接口(暂时适用于1.8版本)执行脚本phantomjs
[options]somescript.js[arg1[arg2[...]]]如果后面没有任何参数,phantomjs
将会进入交互模式Command-lineOptions命令行参数--helpor-hlistsallpossible
command-lineoptions.Haltsimmediately,willnotrunascriptp
assedasargument.列出所有的命令行选项.不执行之后的脚本文件.--versionor-vprintsou
ttheversionofPhantomJS.Haltsimmediately,willnotrunascr
iptpassedasargument.打印出其版本.不执行之后的脚本文件.--cookies-file=/path/to/
cookies.txtspecifiesthefilenametostorethepersistentCooki
es.指定持久储存cookies的文件.--disk-cache=[true|false]enablesdiskcache
(atdesktopservicescachestoragelocation,defaultisfalse).A
lsoaccepted:[yes|no].启用磁盘高速缓存(在桌面服务缓存的存储位置,默认为false)也可接收[yes][n
o]--ignore-ssl-errors=[true|false]ignoresSSLerrors,suchasex
piredorself-signedcertificateerrors(defaultisfalse).Also
accepted:[yes|no].忽略SSL错误,比如过期或自签名的证书错误。(默认为false)也可接收[yes][no]-
-load-images=[true|false]loadallinlinedimages(defaultistru
e).Alsoaccepted:[yes|no].加载所有图片。(默认为true)也可接收[yes][no]--local-
storage-path=/some/pathpathtosaveLocalStoragecontentandWeb
SQLcontent.储存LocalStorage和WebSQL内容的文件路径。--local-storage-quota=nu
mbermaximumsizetoallowfordata.允许数据的最大长度。--local-to-remote-u
rl-access=[true|false]allowslocalcontenttoaccessremoteURL
(defaultisfalse).Alsoaccepted:[yes|no].允许本地内容访问远程URL,默认为fals
e。也可接收[yes][no]。--max-disk-cache-size=sizelimitsthesizeofdis
kcache(inKB).限制磁盘缓存大小(单位为kb)。--output-encoding=encodingsetst
heencodingusedforterminaloutput(defaultisutf8).设置终端输出编码格式
(默认为utf-8)--remote-debugger-portstartsthescriptinadebughar
nessandlistensonthespecifiedport调试脚本端口--remote-debugger-aut
orunrunsthescriptinthedebuggerimmediately:''yes''or''no''(
default)在debugger时候立刻运行脚本--proxy=address:portspecifiestheproxy
servertouse(e.g.--proxy=192.168.1.42:8080).指定要使用的代理服务器。--pro
xy-type=[http|socks5|none]specifiesthetypeoftheproxyserver
(defaultishttp).指定代理服务器类型(默认http)--proxy-authspecifiestheau
thenticationinformationfortheproxy,e.g.--proxy-auth=usernam
e:password).指定代理的认证信息--script-encoding=encodingsetstheencoding
usedforthestartingscript(defaultisutf8).设置脚本的启动编码(默认utf-8
)--ssl-protocol=[sslv3|sslv2|tlsv1|any'']setstheSSLprotocolfo
rsecureconnections(defaultisSSLv3).为安全连接建立SSL协议(默认SSLv3)--ss
l-certificates-path=SetsthelocationforcustomCAcertifi
cates(ifnoneset,usessystemdefault).设置自定义CA证书的位置(设置为空则使用系统默认
)--web-security=[true|false]enableswebsecurityandforbidscro
ss-domainXHR(defaultistrue).Alsoaccepted:[yes|no].开启网络安全,并
禁止跨域XHR(默认开启)也可接收[yes][no]。--webdriver(暂未翻译)startsin''RemoteWeb
Drivermode''(embeddedGhostDriver):''[[:]]''(default''127.0.0.1:
8910'')--webdriver-selenium-grid-hub(暂未翻译)URLtotheSeleniumGri
dHUB:''URLTOHUB''(default''none'')(NOTE:worksonlytogetherwit
h''--webdriver'')自从1.3版本,可以新建一个json文件,将以上配置写入其中,并以这个配置文件启动:--conf
ig=/path/to/config.json请注意:这个json文件中上述选项写法略有所不同:去掉所有的虚线,并且按照驼峰命名法
来书写。并且部分选项名称有所变化。见下例:{/Sameas:--ignore-ssl-errors=true/"i
gnoreSslErrors":true,/Sameas:--max-disk-cache-size=1000/
"maxDiskCacheSize":1000,/Sameas:--output-encoding=utf8/"
outputEncoding":"utf8"/etc./}未直接翻译的选项名称:--disk-cache=>
diskCacheEnabled--load-images=>autoLoadImages--local-stor
age-path=>offlineStoragePath--local-storage-quota=>offline
StorageDefaultQuota--local-to-remote-url-access=>localToRemo
teUrlAccessEnabled--web-security=>webSecurityEnabledphantom
Objectphantom对象phantom.cookies{Object[]}GetorsetCookiesfor
anydomain(though,forsetting,useofphantom.addCookieispre
ferred).TheseCookiesarestoredintheCookieJarandwillbesu
ppliedwhenopeningpertinentWebPages.设置或获取cookies。(用于设置时,其值会被ph
antom.addCookie设置的值覆盖)。Cookies储存在CookieJar中,在打开相关页面时被使用。Thisarra
ywillbepre-populatedbyanyexistingCookiedatastoredinthe
cookiefilespecifiedinthePhantomJSstartupconfig/command-li
neoptions,ifany.这个数列将被在config文件或是命令行中设定的cookie文件数据预填充。phantom.
cookiesEnabled{Boolean}ControlswhethertheCookieJarisenabled
ornot.Defaultstotrue.控制CookieJar是否开启。默认true。phantom.libraryP
ath{String}Thispropertystoresthepathwhichisusedbyinject
Jsfunctiontoresolvethescriptname.Initiallyitissettoth
elocationofthescriptinvokedbyPhantomJS.储存injectJs函数注入脚本时的位
置。最初BALABALA……(没用了)。phantom.version{Object}Read-only.Theversio
noftheexecutingPhantomJSinstance.Examplevalue:{''major'':
1,''minor'':7,''patch'':0}.只读。执行phantomJs实例的版本。addCookie(Object)
{Boolean}AddaCookietotheCookieJar.Returnstrueifsuccessf
ullyadded,otherwisefalse.在CookJar中加入一个Cookie。成功返回true,否则返回fals
e。phantom.addCookie({''name'':''Added-Cookie-Name'',''value'':''Adde
d-Cookie-Value'',''domain'':''.google.com''});clearCookies(){void}D
eleteallCookiesintheCookieJar.删除CookieJar中的Cookies。deleteCoo
kie(cookieName){Boolean}DeleteanyCookiesintheCookieJarwith
a''name''propertymatchingcookieName.Returnstrueifsuccessfu
llydeleted,otherwisefalse.删除与名称相配的Cookies。成功返回true,否则返回false。p
hantom.exit(returnValue){void}Exitstheprogramwiththespecifi
edreturnvalue.Ifnoreturnvalueisspecified,itissetto0.
带有指定返回值的结束程序。默认为0.if(somethingIsWrong){phantom.exit(1);}else
{phantom.exit(0);}phantom.injectJs(filename){boolean}Injectsex
ternalscriptcodefromthespecifiedfileintothePhantomouter
space.Ifthefilecannotbefoundinthecurrentdirectory,lib
raryPathisusedforadditionallookup.Thisfunctionreturnstr
ueifinjectionissuccessful,otherwiseitreturnsfalse.从Phanto
m外部空间注入指定文件的脚本代码。如果当前目录下未发现,将从libraryPath指定的位置查找。注入成功返回true,失败返回f
alse。varwasSuccessful=phantom.injectJs(''lib/utils.js'');page.on
ErrorThiscallbackisinvokedwhenthereisaJavaScriptexecutio
nerrornotcaughtbyapage.onErrorhandler.Thisistheclosest
itgetstohavingaglobalerrorhandlerinPhantomJS,andsoit
isabestpracticetosetthisonErrorhandlerupinordertoca
tchanyunexpectedproblems.Theargumentspassedtothecallback
aretheerrormessageandthestacktrace[asanArray].当页面有未能处理
的脚本错误时调用这个回调函数。这个函数最先得到phantomJs中处理的全局错误,所以最好的方法是设置出错处理程序以捕捉任何意想不
到的问题。传递的参数是错误消息和堆栈追踪(其为一个数组)。phantom.onError=function(msg,trac
e){varmsgStack=[''PHANTOMERROR:''+msg];if(trace&&trace
.length){msgStack.push(''TRACE:'');trace.forEach(function(t){m
sgStack.push(''->''+(t.file||t.sourceURL)+'':''+t.line+(
t.function?''(infunction''+t.function+'')'':''''));});}con
sole.error(msgStack.join(''\n''));phantom.exit(1);};WebPageModul
eWeb页面模块Tostartusing,youmustrequireareferencetothewebp
agemodulethenuseittocreateaninstance:开始使用之前,你必须请求一个webpag
e模块的引用,并创造一个实例:varwebPage=require(''webpage'');varpage=webPa
ge.create();canGoBackcanGoForwardclipRect{object}Thispropertyd
efinestherectangularareaofthewebpagetoberasterizedwhen
page.renderisinvoked.Ifnoclippingrectangleisset,page.re
nderwillprocesstheentirewebpage.这个属性定义了一个网页的矩形裁剪区域。供page.re
nder函数调用。如果没有设置裁剪区域,page.render将处理整个网页。varwebPage=require(''web
page'');varpage=webPage.create();page.clipRect={top:14,lef
t:3,width:400,height:300};content{string}Thispropertystor
esthecontentofthewebpage(mainframe),enclosedinanHTML/
XMLelement.Settingthepropertywilleffectivelyreloadtheweb
pagewiththenewcontent.Seealsopage.plainTexttogetthecon
tentwithoutanyHTMLtags.此属性存储网页的内容(主要frame),包裹在一个HTML/XML元素中。设
置这个属性将有效地以新内容重新加载网页。Page.plainText将获得没有HTML标签的内容。varwebPage=re
quire(''webpage'');varpage=webPage.create();page.open(''http://ph
antomjs.org'',function(status){varcontent=page.content;con
sole.log(''Content:''+content);phantom.exit();});CookiesGetor
setCookiesvisibletothecurrentURL(though,forsetting,use
ofpage.addCookieispreferred).Thisarraywillbepre-populated
byanyexistingCookiedatavisibletothisURLthatisstoredi
ntheCookieJar,ifany.对当前URL设置Cookie可见或获取之,(然而就设置而言更推荐使用page.ad
dcookie)。如果cookieJar中有cookie,并且对此URL可见,那么这些cookie数据将会预加载。Cookies
isanarrayofobjects:javascript{domain:''example.com'',expir
es:''SatOct11201421:44:33GMT+0200(CEST)'',expiry:147612861
8,httponly:false,name:''cookieName'',path:''/'',secure:false,
value:cookieValue}customHeaders{object}Thispropertyspecifie
sadditionalHTTPrequestheadersthatwillbesenttotheserver
foreveryrequestissued(forpages?and?resources).Thedefault
valueisanemptyobject?{}.Headersnamesandvaluesgetencoded
inUS-ASCIIbeforebeingsent.Pleasenotethatthe''User-Agent''
shouldbesetusingthe?page.settings,settingthe''User-Agent''
propertyinthispropertywilloverwrite?thevaluesetvia?page.s
ettings.这个属性为每一个发出的请求指定额外的发送到服务器HTTP请求头(页面和资源)。默认值是一个空对象{}。Header
s发送之前会用US_ASCII码编码。请注意:’User-Agent’应该使用page.settings来设置;如果设置’User
-Agent’属性,则通过page.settings设置的属性将被重写。varwebPage=require(''webpag
e'');varpage=webPage.create();page.customHeaders={"X-Test":
"foo","DNT":"1"};DoyouonlywantthesecustomHeaderspassedto
theinitialpage.openrequest?你只想让这些headers只传递到初始page.open请求吗?va
rwebPage=require(''webpage'');varpage=webPage.create();page.c
ustomHeaders={"X-Test":"foo","DNT":"1"};page.onInitialized
=function(){page.customHeaders={};};EventfocusedFrameNamefra
meContent{string}Thispropertystoresthecontentofthewebpag
e''scurrentlyactiveframe(whichmayormaynotbethemainfram
e),enclosedinanHTML/XMLelement.Settingthepropertywilleff
ectivelyreloadthewebpagewiththenewcontent.此属性存储页面当前活动的fra
me内容(这可能不是主要frame),包裹在一个html/xml元素中。设置这个属性将会用新的内容有效地重新加载网页。frameN
ameframePlainText{string}Read-only.Thispropertystoresthecon
tentofthewebpage''scurrentlyactiveframe(whichmayormayn
otbethemainframe)asplaintext—noelementtags!只读。这个属性存储页面
当前活动的frame内容(这可能不是主要框架)——纯文本,没有元素标签。frameTitleframeUrl{string}Re
ad-only.ThispropertygetsthecurrentURLofthewebpage''scur
rentlyactiveframe(whichmayormaynotbethemainframe).只读。此
属性获取当前Web页面活动frame的URL,(这个frame可能不是主要的frame)framesCountframesName
Returnsarraywithframesnames.返回frame名称组成的数组。libraryPath?{stri
ng}Thispropertystoresthepathwhichisusedby?page.injectJs?f
unctiontoresolvethescriptname.Initiallyitissettotheloc
ationofthescriptinvokedbyPhantomJS.此属性存储由page.injectjs函数调用脚
本的路径名。最初balabala……navigationLocked{boolean}Thispropertydefines
whethernavigationawayfromthepageispermittedornot.Ifit
issettotrue,thenthepageislockedtothecurrentURL.Defa
ultstofalse.这个属性定义是否允许离开页面。如果设置为true,那么页面将被锁定到当前URL。默认值为false。o
fflineStoragePathofflineStorageQuotaownsPagespagespagesWindowName
paperSize{object}Thispropertydefinesthesizeofthewebpage
whenrenderedasaPDF.这个属性定义网页呈现为一个PDF时的尺寸。plainText{string}Rea
d-only.Thispropertystoresthecontentofthewebpage(mainfr
ame)asplaintext—noelementtags!Seealso:page.contentwhich
returnsthecontentwithelementtags.只读。此属性存储网页(主frame)内容为纯文本——
没有元素标签。参见:page.content返回带元素标签的内容。scrollPosition?{object}Thisprop
ertydefinesthescrollpositionofthewebpage.这个属性定义网页的滚动位置。va
rwebPage=require(''webpage'');varpage=webPage.create();page.s
crollPosition={top:100,left:0};settings{object}Thisproper
tystoresvarioussettingsofthewebpage:此属性存储网页的各种设置:javascrip
tEnableddefineswhethertoexecutethescriptinthepageornot
(defaultstotrue).确定是否在页面执行脚本(默认为true)loadImagesdefineswhethe
rtoloadtheinlinedimagesornot(defaultstotrue).确定是否加载图片(默
认为true)localToRemoteUrlAccessEnableddefineswhetherlocalresour
ce(e.g.fromfile)canaccessremoteURLsornot(defaultstofa
lse).确定本地资源(如文件资源)可以访问远程URL(默认为false)userAgentdefinestheusera
gentsenttoserverwhenthewebpagerequestsresources.定义当page请
求资源时发送给服务器的user-agent。userNamesetstheusernameusedforHTTPa
uthentication.设置用于http授权的用户姓名。passwordsetsthepasswordusedfor
HTTPauthentication.设置用于http授权的用户密码。XSSAuditingEnableddefinesw
hetherloadrequestsshouldbemonitoredforcross-sitescripting
attempts(defaultstofalse).定义是否监控加载的请求以防其为跨站脚本攻击。(默认为false)web
SecurityEnableddefineswhetherwebsecurityshouldbeenabledor
not(defaultstotrue).定义是否开启网页安全(默认为true)resourceTimeout(inmi
lli-secs)definesthetimeoutafterwhichanyresourcerequested
willstoptryingandproceedwithotherpartsofthepage.onReso
urceTimeoutcallbackwillbecalledontimeout.超时时间(毫秒)任何资源请求在超时以
后停止,并继续进行其余页面的部分。onResourceTimeout回调函数将会在超时以后被调用。Note:Thesettin
gsapplyonlyduringtheinitialcalltothepage.openfunction.
Subsequentmodificationofthesettingsobjectwillnothaveany
impact.注意:该设置仅适用于page.open函数初始化期间。后续修改不会受到此影响。varwebPage=requi
re(''webpage'');varpage=webPage.create();page.settings.userAgent
=''Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML
,likeGecko)Chrome/37.0.2062.120Safari/537.36'';titlepage.open(
''http://phantomjs.org'',function(status){console.log(page.titl
e);//getpageTitlephantom.exit();});url{string}Read-only.Th
ispropertygetsthecurrentURLofthewebpage(mainframe).var
webPage=require(''webpage'');varpage=webPage.create();page.op
en(''http://phantomjs.org'',function(status){varurl=page.url
;console.log(''URL:''+url);phantom.exit();});viewportSize{obj
ect}Thispropertysetsthesizeoftheviewportforthelayoutpr
ocess.Itisusefultosetthepreferredinitialsizebeforeload
ingthepage,e.g.tochoosebetween''landscape''vs''portrait''.这个
属性设置布局过程中的视窗大小。这被用于在加载页面之前首选的初始值大小。例如从landsscape和portrait之前选择。Bec
ausePhantomJSisheadless(nothingisshown),viewportSizeeffec
tivelysimulatesthesizeofthewindowlikeinatraditionalbro
wser.因为Phantomjs是个无界面浏览器(不显示任何东西),windowNamezoomFactor{number}Th
ispropertyspecifiesthescalingfactorforthepage.renderand
page.renderBase64functions.Thedefaultis1,i.e.100%zoom.这个缩放
因子指定page.render和page.renderBase64函数的缩放程度。默认为1,即百分之百缩放。varwebPage
=require(''webpage'');varpage=webPage.create();page.zoomFactor
=0.25;page.render(''capture.png'');addCookie(Cookie){boolean}Add
aCookietothepage.Ifthedomaindoesnotmatchthecurrentp
age,theCookiewillbeignored/rejected.Returnstrueifsuccess
fullyadded,otherwisefalse.给页面添加一个cookie。如果域名不匹配当前页,cookie将被忽略或
拒绝。如果成功返回true。否则false。varwebPage=require(''webpage'');varpage=
webPage.create();phantom.addCookie({''name'':''Valid-Cookie-
Name'',/requiredproperty/''value'':''Valid-Cookie-Value
'',/requiredproperty/''domain'':''localhost'',''path''
:''/foo'',/requiredproperty/''httponly'':tru
e,''secure'':false,''expires'':(newDate()).getTime()+(100
06060)/<--expiresin1hour/});clearCookies()?{void
}DeleteallCookiesvisibletothecurrentURL.删除对当前URL可见的cookie。
close(){void}Closethepageandreleasesthememoryheapassocia
tedwithit.Donotusethepageinstanceaftercallingthis.关闭pa
ge,释放相关的内存。调用这个方法以后不再使用这个页面实例。Duetosometechnicallimitations,
thewebpageobjectmightnotbecompletelygarbagecollected.Th
isisoftenencounteredwhenthesameobjectisusedoverandove
ragain.Callingthisfunctionmaystoptheincreasingheapalloc
ation.由于一些技术上的限制,网页对象的垃圾收集可能不完全,导致经常出现同一对象的反复调用。调用此函数可以阻止越来越多的内存分
配。deleteCookie(cookieName){boolean}DeleteanyCookiesvisibleto
thecurrentURLwitha''name''propertymatchingcookieName.Retu
rns?true?ifsuccessfullydeleted,otherwise?false.删除一个对当前URL可见的,n
ame属性为cookieName的cookie。成功返回true,否则false。varwebPage=require(''w
ebpage'');varpage=webPage.create();page.deleteCookie(''Added-Coo
kie-Name'');evaluate(function,arg1,arg2,...){object}Evaluates
thegivenfunctioninthecontextofthewebpage.Theexecution
issandboxed,thewebpagehasnoaccesstothephantomobjectan
ditcan''tprobeitsownsetting.在当前Web页面上下文中执行给予的函数。这个函数执行在沙箱中,w
eb页面无法访问phantom的上下文和设置。GetthepagetitlefromBing.com(1)varwe
bPage=require(''webpage'');varpage=webPage.create();page.open(
''http://m.bing.com'',function(status){vartitle=page.evaluate
(function(){returndocument.title;});console.log(title);phan
tom.exit();});GetthepagetitlefromBing.com(2)AsofPhantomJS
1.6,JSON-serializableargumentscanbepassedtothefunction.
Inthefollowingexample,thetextvalueofaDOMelementisextr
acted.(自从phantom1.6)Json字符串可以传递给函数。在下面的例子中,一个dom元素的textvalue被提出
了出来。Thefollowingexampleachievesthesameendgoalastheprevi
ousexamplebuttheelementischosenbasedonaselectorwhichi
spassedtotheevaluatecall:下面的例子实现和之前的例子相同的目标,然而这个元素是基于一个传递到ev
aluate中的选择器选择的。page.open(''http://m.bing.com'',function(status){
vartitle=page.evaluate(function(s){returndocument.querySele
ctor(s).innerText;},''title'');console.log(title);phantom.exit(
);});Note:Theargumentsandthereturnvaluetotheevaluatefun
ctionmustbeasimpleprimitiveobject.Theruleofthumb:ifit
canbeserializedviaJSON,thenitisfine.Note:传给evaluate的参数和返
回值必须是一个简单的原始对象。经验之谈:如果它可以序列化成json,那么它就是合适的。Closures,functions,D
OMnodes,etc.willnotwork!闭包,函数,DOM节点等等都是无法工作的!evaluateAsync(f
unction)?{void}Evaluatesthegivenfunctioninthecontextofthe
webpagewithoutblockingthecurrentexecution.Thefunctionre
turnsimmediatelyandthereisnoreturnvalue.Thisisusefulto
runsomescriptasynchronously.在web页面上下文无阻塞立刻执行给定的函数。该函数立刻返回,没有返
回值。在异步执行一些脚本时有用。getPage(windowName)go(index)goBack()goForward()in
cludeJs(url,callback){void}Includesexternalscriptfromthesp
ecifiedurl(usuallyaremotelocation)onthepageandexecutes
thecallbackuponcompletion.将指定URL(通常是一个远程地址)上的脚本包括进这个page,完成后回调
。varwebPage=require(''webpage'');varpage=webPage.create();pag
e.includeJs(''http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jq
uery.min.js'',function(){//jQueryisloaded,nowmanipulateth
eDOMvar$loginForm=$(''form#login'');$loginForm.find(''input[na
me="username"]'').value(''phantomjs'');$loginForm.find(''input[name=
"password"]'').value(''c45p3r'');});injectJs(filename){boolean}Inje
ctsexternalscriptcodefromthespecifiedfileintothepage(l
ikepage.includeJs,exceptthatthefiledoesnotneedtobeacce
ssiblefromthehostedpage).Ifthefilecannotbefoundinthec
urrentdirectory,libraryPathisusedforadditionallookup.This
functionreturnstrueifinjectionissuccessful,otherwiseitr
eturnsfalse.以特殊文件向页面注入脚本代码(类似page.indudejs,除了这个文件不需要从hostedpage
获取。)如果不能在当前文件夹中找到文件,程序将会去libraryPath路径下寻找。如果注入成功,返回true;否则返回false
。varwebPage=require(''webpage'');varpage=webPage.create();pag
e.open(''http://www.phantomjs.org'',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'')){vartitle=page.evaluate(function(){//returnTitle
isafunctionloadedfromourdo.jsfile-seebelowreturnretu
rnTitle();});console.log(title);phantom.exit();}});}});open
(url,callback){void}open(url,method,callback){void}open(ur
l,method,data,callback){void}open(url,settings,callback){
void}Opensthe?url?andloadsittothepage.Oncethepageisloa
ded,theoptional?callback?iscalledusing?page.onLoadFinished,a
ndalsoprovidesthepagestatustothefunction(''success''?or?''f
ail'').打开并加载URL到页面。一旦加载完页面,使用page.onloadFinished调用可能会有的回调。并且提供给该函数
success或者fail的状态。GETgoogle.comandreport"success"or"fail":va
rwebPage=require(''webpage'');varpage=webPage.create();page.o
pen(''http://www.google.com/'',function(status){console.log(''Sta
tus:''+status);//Dootherthingshere...});POSTdatatogoogl
e.comandreport"success"or"fail":AsofPhantomJS1.2,theope
nfunctioncanbeusedtorequestaURLwithmethodsotherthanG
ET.Thissyntaxalsoincludestheabilitytospecifydatatobes
entwiththerequest.Inthefollowingexample,wemakearequest
usingthePOSTmethod,andincludesomebasicdata.自从1.2版本开始,ope
n函数还可用于不止GET方式请求URL。这个语法还包括传输数据给药发送的请求的能力。下面是一个使用POST方法的例子,包括一些基本
的数据。varwebPage=require(''webpage'');varpage=webPage.create();
varpostBody=''user=username&password=password'';page.open(''http:
//www.google.com/'',''POST'',postBody,function(status){console.
log(''Status:''+status);//Dootherthingshere...});POSTjson
datatoyour.custom.apiinutf-8encoding:AsofPhantomJS1.9,th
eopenfunctioncangetanobjectofsettings.andwithauseof
"encoding"key,youcansetthecustomencodingtoyourapp.Int
hisexample,we''vesettheencodingtoUTF8,andsettheContent-
Typeheadertoapplication/jsonformakingourserverknowthere
questhasinformationinjsonformatandnotinurlencodedformat
.从1.9版本开始,open函数可以得到一个settings对象。使用“encoding”键,你可以设置应用的自定义编码。在这个例
子中,我们设置编码为“utf-8”并且为application/json设置Conten-Typeheader,以便于让服务端明
白这个请求Json格式,不出现乱码。varwebPage=require(''webpage'');varpage=web
Page.create();varsettings={operation:"POST",encoding:"utf8
",headers:{"Content-Type":"application/json"},data:JSON.st
ringify({some:"data",another:["custom","data"]})};page.open
(''http://your.custom.api'',settings,function(status){console.l
og(''Status:''+status);//Dootherthingshere...});openUrl(url
,httpConf,settings)reloadrender(filename[,{format,quality}])
{void}Rendersthewebpagetoanimagebufferandsavesitasth
especifiedfilename.Currently,theoutputformatisautomaticall
ysetbasedonthefileextension.将网页保存为指定文件名的突变,目前输出格式自动设置为文件扩展名
。SupportedformatsPNGGIFJPEGPDFQualityAnintegerbetween0and
100.varwebPage=require(''webpage'');varpage=webPage.create()
;page.viewportSize={width:1920,height:1080};page.open("htt
p://www.google.com",functionstart(status){page.render(''google
_home.jpeg'',{format:''jpeg'',quality:''100''});phantom.exit();})
;renderBase64(format)Rendersthewebpagetoanimagebufferand
returnstheresultasaBase64-encodedstringrepresentationoft
hatimage.将网页保存成图片buffer,并以base64编码字符串返回该图片。SupportedformatsPNG
GIFJPEGvarwebPage=require(''webpage'');varpage=webPage.creat
e();page.viewportSize={width:1920,height:1080};page.open(''h
ttp://phantomjs.org'',function(status){varbase64=page.rende
rBase64(''PNG'');console.log(base64);phantom.exit();});sendEventS
endsaneventtothewebpage.给页面发送个事件。Theeventsarenotsynthet
icDOMevents,eacheventissenttothewebpageasifitcomes
aspartofuserinteraction.这个事件并不是虚拟DOM事件,每一个事件被当作用户的交互发送到web页。
MouseeventssendEvent(mouseEventType[,mouseX,mouseY,button=''le
ft''])Thefirstargumentistheeventtype.Supportedtypesare''m
ouseup'',''mousedown'',''mousemove'',''doubleclick''and''click''.The
nexttwoargumentsareoptionalbutrepresentthemouseposition
fortheevent.Thebuttonparameter(defaultstoleft)specifies
thebuttontopush.For''mousemove'',however,thereisnobuttonp
ressed(i.e.itisnotdragging).第一个参数是事件类型。支持的类型有“mouseup”,“mous
edown”,“mousemove”,“doubleclick”和“click”。接下来的两个可选参数代表了这个事件的鼠标位置。B
utton参数(默认为左)规定了哪个按钮被按下。然而对于“mousemove”事件是没有按钮被按下的。(不是拖拽。)Keyboar
deventssendEvent(keyboardEventType,keyOrKeys,[null,null,modi
fier])Thefirstargumentistheeventtype.Thesupportedtypesa
re:keyup,keypressandkeydown.Thesecondparameterisakey(f
rompage.event.key),orastring.第一个参数是事件类型。支持的类型有:“keyup”“keypre
ss”和“keydown”。第二个参数是个按键(通过page.event.key),或者一个string.Youcanalso
indicateafifthargument,whichisanintegerindicatingthemo
difierkey.你也可以加第五个参数,它是一个用来修饰key的整数。0:Nomodifierkeyispresse
d0x02000000:AShiftkeyonthekeyboardispressed0x04000000:A
Ctrlkeyonthekeyboardispressed0x08000000:AnAltkeyonthe
keyboardispressed0x10000000:AMetakeyonthekeyboardispres
sed0x20000000:AkeypadbuttonispressedThirdandfourthargumen
tarenottakenaccountforkeyboardevents.Justgivenullfort
hem.第三个和第四个参数不对键盘事件起作用,给他们设置为null好了。varwebPage=require(''webpag
e'');varpage=webPage.create();page.sendEvent(''keypress'',page.e
vent.key.A,null,null,0x02000000|0x08000000);setContentAllows
tosetbothpage.contentandpage.urlproperties.Thewebpagewil
lbereloadedwiththenewcontentandthecurrentlocationseta
sthegivenurl,withoutanyactualhttprequestbeingmade.允许同时设
置page.Content和page.url的属性。网页会重新加载一个新的内容,并且当前url被设置为被给予的URL。Stopsw
itchToFocusedFrameswitchToFrame(frameName)orswitchToFrame(frame
Position)switchToMainFrameswitchToParentFrameuploadFile(selector,
filename)Uploadsthespecifiedfile(filename)totheformeleme
ntassociatedwiththeselector.将指定的文件(文件名)上传给选择器选择的form元素。Thisf
unctionisusedtoautomatetheuploadofafile,whichisusuall
yhandledwithafiledialoginatraditionalbrowser.Sincether
eisnodialoginthisheadlessmode,suchanuploadmechanismis
handledviathisspecialfunctioninstead.这个函数用来执行一个文件上传。这通常通过传统
浏览器里的一个文件对话框处理。既然这个浏览器没有界面,这样一个上传机制就由一个函数所代替。varwebPage=requir
e(''webpage'');varpage=webPage.create();page.uploadFile(''input[n
ame=image]'',''/path/to/some/photo.jpg'');CallbackTriggersThesefu
nctionscallcallbacks,usedfortests...closing(page)initialized
()javaScriptAlertSent(message)javaScriptConsoleMessageSent(messag
e)loadFinished(status)loadStarted()navigationRequested(url,navig
ationType,navigationLocked,isMainFrame)rawPageCreated(page)reso
urceError(resource)resourceReceived(request)resourceRequested(res
ource)urlChanged(url)onAlertThiscallbackisinvokedwhentherei
saJavaScriptalertonthewebpage.Theonlyargumentpassedto
thecallbackisthestringforthemessage.Thereisnoreturnv
alueexpectedfromthecallbackhandler.当webpage有javascript的ale
rt()出现时调用此回调。唯一的传递给回调的参数是消息的字符串。这个回调函数没有任何返回。varwebPage=requir
e(''webpage'');varpage=webPage.create();page.onAlert=function(
msg){console.log(''ALERT:''+msg);};onClosingThiscallbackisi
nvokedwhentheWebPageobjectisbeingclosed,eitherviapage.c
loseinthePhantomJSouterspaceorviawindow.closeinthepage
''sclient-side.Itisnotinvokedwhenchild/descendantpagesare
beingclosedunlessyoualsohookthemupindividually.Ittakes
oneargument,closingPage,whichisareferencetothepagethat
isclosing.OncetheonClosinghandlerhasfinishedexecuting(re
turned),theWebPageobjectclosingPagewillbecomeinvalid.当网页对象
被关闭时调用这个回调函数。phantomJs的环境中通过page.close和在页面中通过window.close关闭页面时触发。
当子页面关闭时并不调用此函数,当你单独打开他们时调用此函数。Closingpage参数指向正在关闭的页面。varwebPage
=require(''webpage'');varpage=webPage.create();page.onClosing=
function(closingPage){console.log(''Thepageisclosing!URL:''
+closingPage.url);};onConfirmThiscallbackisinvokedwhenther
eisaJavaScriptconfirmonthewebpage.Theonlyargumentpass
edtothecallbackisthestringforthemessage.Thereturnvalu
eofthecallbackhandlercanbeeithertrueorfalse,whichare
equivalenttopressingthe"OK"or"Cancel"buttonspresentedin
aJavaScriptconfirm,respectively.当网页上有一个javascript的confirm函数出现
时调用此回调。唯一一个被传送到回调函数的参数是消息的字符串。回调函数的返回值是true或者false,相当于在javascript
环境下按下了一个确认按钮或者取消按钮。varwebPage=require(''webpage'');varpage=we
bPage.create();page.onConfirm=function(msg){console.log(''CONF
IRM:''+msg);returntrue;//`true`===pressingthe"OK"butto
n,`false`===pressingthe"Cancel"button};onConsoleMessageThis
callbackisinvokedwhenthereisaJavaScriptconsolemessageo
nthewebpage.Thecallbackmayacceptuptothreearguments:th
estringforthemessage,thelinenumber,andthesourceidentif
ier.当页面javascript打印消息时调用此函数。这个回调函数接收三个参数(后两个已经取消):消息(string),行数(n
umber)(已取消),和元标识符(已取消)。Bydefault,consolemessagesfromtheweb
pagearenotdisplayed.Usingthiscallbackisatypicalwaytor
edirectit.默认的,网页打印台上显示的文字不会展示出来。使用这个回调是一种间接方法。Note:linenumber
andsourceidentifierarenotusedyet,atleastinphantomJS<=
1.8.1.Youreceiveundefinedvalues.varwebPage=require(''webpag
e'');varpage=webPage.create();page.onConsoleMessage=function(
msg,lineNum,sourceId){console.log(''CONSOLE:''+msg+''(from
line#''+lineNum+''in"''+sourceId+''")'');};onErrorThiscal
lbackisinvokedwhenthereisaJavaScriptexecutionerror.Iti
sagoodwaytocatchproblemswhenevaluatingascriptinthewe
bpagecontext.Theargumentspassedtothecallbackaretheerro
rmessageandthestacktrace[asanArray].当有一个javascript执行错误时调用
此回调函数。它是当web页面上下文脚本发生错误时候捕获错误的好办法。传递给回掉函数的参数是错误消息和堆栈追踪【数组】varweb
Page=require(''webpage'');varpage=webPage.create();page.onErro
r=function(msg,trace){varmsgStack=[''ERROR:''+msg];if(
trace&&trace.length){msgStack.push(''TRACE:'');trace.forEach(f
unction(t){msgStack.push(''->''+t.file+'':''+t.line+(t.f
unction?''(infunction"''+t.function+''")'':''''));});}cons
ole.error(msgStack.join(''\n''));};onFilePickervarwebPage=requir
e(''webpage'');varpage=webPage.create();varsystem=require(''sy
stem'');page.onFilePicker=function(oldFile){if(system.os.name
===''windows''){return''C:\\Windows\\System32\\drivers\\etc\\ho
sts'';}return''/etc/hosts'';};onInitializedThiscallbackisinvok
edafterthewebpageiscreatedbutbeforeaURLisloaded.The
callbackmaybeusedtochangeglobalobjects.当页面创建但是url尚未加载时调用此函
数。回调也许会被用来改变全局变量。varwebPage=require(''webpage'');varpage=webP
age.create();page.onInitialized=function(){page.evaluate(func
tion(){document.addEventListener(''DOMContentLoaded'',function()
{console.log(''DOMcontenthasloaded.'');},false);});};onLoad
FinishedThiscallbackisinvokedwhenthepagefinishestheloadi
ng.Itmayacceptasingleargumentindicatingthepage''sstatus:
''success''ifnonetworkerrorsoccurred,otherwise''fail''.页面完成加载
时调用此回调函数。回调函数接收一个参数表示网页的状态:success表示没有网络错误发生,不然是fail。Alsoseepag
e.openforanalternatehookfortheonLoadFinishedcallback.var
webPage=require(''webpage'');varpage=webPage.create();page.onL
oadFinished=function(status){console.log(''Status:''+status)
;//Dootherthingshere...};page.onLoadFinished=function(stat
us){console.log(''Status:''+status);//Dootherthingshere..
.};onLoadStartedThiscallbackisinvokedwhenthepagestartsthe
loading.Thereisnoargumentpassedtothecallback.当页面开始加载时调用此
函数。没有参数传递给回调。varwebPage=require(''webpage'');varpage=webPage.
create();page.onLoadStarted=function(){varcurrentUrl=page.
evaluate(function(){returnwindow.location.href;});console.lo
g(''Currentpage''+currentUrl+''willgone...'');console.log(''N
owloadinganewpage...'');};onNavigationRequestedByimplementing
thiscallback,youwillbenotifiedwhenanavigationeventhapp
ensandknowifitwillbeblocked(bypage.navigationLocked).通过调
用这一个回调函数,当导航事件发生时你将会得到通知,并且知道这个是否会被阻塞(通过page.navigationLocked)。Ar
gumentsurl:ThetargetURLofthisnavigationevent导航事件的目标URLtyp
e:Possiblevaluesinclude:''Undefined'',''LinkClicked'',''FormSub
mitted'',''BackOrForward'',''Reload'',''FormResubmitted'',''Other''可能值
:''Undefined'',''LinkClicked'',''FormSubmitted'',''BackOrForward'',''R
eload'',''FormResubmitted'',''Other''willNavigate:trueifnavigati
onwillhappen,falseifitislocked(bypage.navigationLocked)t
rue当导航发生,被(通过page.navigationLocked)锁住时是falsemain:trueifthise
ventcomesfromthemainframe,falseifitcomesfromaniframe
ofsomeothersub-frame.当这个事件来自主页面时为true,否则是false。varwebPage=r
equire(''webpage'');varpage=webPage.create();page.onNavigationRe
quested=function(url,type,willNavigate,main){console.log(''
Tryingtonavigateto:''+url);console.log(''Causedby:''+type
);console.log(''Willactuallynavigate:''+willNavigate);consol
e.log(''Sentfromthepage\''smainframe:''+main);}onPageCreated
Thiscallbackisinvokedwhenanewchildwindow(but?not?deeper
descendantwindows)iscreatedbythepage,e.g.using?https://de
veloper.mozilla.org/docs/DOM/window.openwindow.open.页面创建新的子窗口的时候调
用此回调。例如使用window.openInthePhantomJSouterspace,thisWebPageob
jectwillnotyethavecalleditsownpage.openmethodyetandth
usdoesnotyetknowitsrequestedURL(page.url).在phantomjs的外部环境
这个webpage对象尚未访问自己的page.open方法,所以它还不知道请求的URL。Therefore,themost
commonpurposeforutilizingapage.onPageCreatedcallbackisto
decoratethepage(e.g.hookupcallbacks,etc.).因此,page.onpageCr
eated最常见的用途是装饰页面。varwebPage=require(''webpage'');varpage=webP
age.create();page.onPageCreated=function(newPage){console.log
(''Anewchildpagewascreated!ItsrequestedURLisnotyetavai
lable,though.'');//DecoratenewPage.onClosing=function(closin
gPage){console.log(''Achildpageisclosing:''+closingPage.ur
l);};};onPromptThiscallbackisinvokedwhenthereisaJavaScri
ptpromptonthewebpage.Theargumentspassedtothecallbacka
rethestringforthemessage(msg)andthedefaultvalue(defaul
tVal)forthepromptanswer.Thereturnvalueofthecallbackhan
dlershouldbeastring.当网页端有javascript的prompt()时调用此函数。传给回调函数的参数
是msg消息和prompt()回答的默认值。返回值应该是string格式。varwebPage=require(''webpa
ge'');varpage=webPage.create();page.onPrompt=function(msg,de
faultVal){if(msg==="What''syourname?"){return''PhantomJS''
;}returndefaultVal;};onResourceErrorThiscallbackisinvokedw
henawebpagewasunabletoloadresource.Theonlyargumentto
thecallbackistheresourceErrormetadataobject.当一个页面无法加载资源时调用此
函数。传给回掉函数的参数是resourceerror元数据对象。TheresourceErrormetadataobject
containstheseproperties:resourceError元数据含有下列属性:id:thenumber
oftherequesturl:theresourceurlerrorCode:theerrorcodeer
rorString:theerrordescriptionvarwebPage=require(''webpage'')
;varpage=webPage.create();page.onResourceError=function(reso
urceError){console.log(''Unabletoloadresource(#''+resourceE
rror.id+''URL:''+resourceError.url+'')'');console.log(''Errorc
ode:''+resourceError.errorCode+''.Description:''+resourceEr
ror.errorString);};onResourceReceivedThiscallbackisinvokedwhe
naresourcerequestedbythepageisreceived.Theonlyargument
tothecallbackistheresponsemetadataobject.当页面请求的资源收到时调用回调。
传给回调的参数是resourceerror元数据对象。Iftheresourceislargeandsentbyt
heserverinmultiplechunks,onResourceReceivedwillbeinvoked
foreverychunkreceivedbyPhantomJS.当资源过大时服务端将会分成多块传送资源。onResou
rceReceived()将会在每一块数据被PhantomJs接收时调用。Theresponsemetadataobject
containstheseproperties:id:thenumberoftherequestedresou
rceurl:theURLoftherequestedresourcetime:Dateobjectcont
ainingthedateoftheresponseheaders:listofhttpheadersbody
Size:sizeofthereceivedcontentdecompressed(entirecontent
orchunkcontent)contentType:thecontenttypeifspecifiedredir
ectURL:ifthereisaredirection,theredirectedURLstage:"st
art","end"(FIXME:othervalueforintermediatechunk?)status:
httpstatuscode.ex:200statusText:httpstatustext.ex:OKvar
webPage=require(''webpage'');varpage=webPage.create();page.on
ResourceReceived=function(response){console.log(''Response(#''
+response.id+'',stage"''+response.stage+''"):''+JSON.str
ingify(response));};onResourceRequestedThiscallbackisinvokedw
henthepagerequestsaresource.Thefirstargumenttothecallb
ackistherequestDatametadataobject.Thesecondargumentisth
enetworkRequestobjectitself.页面请求资源时调用此函数。第一个参数是resourceerror元数
据对象,第二个参数是networkRequest对象本身。TherequestDatametadataobjectcont
ainstheseproperties:id:thenumberoftherequestedresourceme
thod:httpmethodurl:theURLoftherequestedresourcetime:D
ateobjectcontainingthedateoftherequestheaders:listofht
tpheadersThenetworkRequestobjectcontainsthesefunctions:abor
t():abortsthecurrentnetworkrequest.Abortingthecurrentne
tworkrequestwillinvokeonResourceErrorcallback.终止当前的网络请求,将会调用
回调函数onResourceError。changeUrl(newUrl):changesthecurrentURLo
fthenetworkrequest.BycallingnetworkRequest.changeUrl(newUrl
),wecanchangetherequesturltothenewurl.Thisisanexcel
lentandonlywaytoprovidealternativeimplementationofaremo
teresource.(seeExample-2)改变当前网络请求的URL。这是提供一个远程资源替代实现的唯一途径。setH
eader(key,value)ExamplesExample-1varwebPage=require(''webpage''
);varpage=webPage.create();page.onResourceRequested=function
(requestData,networkRequest){console.log(''Request(#''+reques
tData.id+''):''+JSON.stringify(requestData));};Example-2Provid
eanalternativeimplementationofaremotejavascript.varwebPag
e=require(''webpage'');varpage=webPage.create();page.onResourc
eRequested=function(requestData,networkRequest){varmatch=
requestData.url.match(/wordfamily.js/g);if(match!=null){con
sole.log(''Request(#''+requestData.id+''):''+JSON.stringify(r
equestData));//newWordFamily.jsisanalternativeimplementatio
nofwordFamily.js//andisavailableinlocalpathnetworkReque
st.changeUrl(''newWordFamily.js'');}};onResourceTimeoutThiscallb
ackisinvokedwhenaresourcerequestedbythepagetimeoutacco
rdingtosettings.resourceTimeout.Theonlyargumenttothecallb
ackistherequestmetadataobject.页面请求的资源超时调用此函数。传给回调函数的唯一参数是请求元
数据对象。Therequestmetadataobjectcontainstheseproperties:id:th
enumberoftherequestedresourcemethod:httpmethodurl:theURL
oftherequestedresourcetime:Dateobjectcontainingthedateo
ftherequestheaders:listofhttpheaderserrorCode:theerrorco
deoftheerrorerrorString:textmessageoftheerrorExamplesvar
webPage=require(''webpage'');varpage=webPage.create();page.onR
esourceTimeout=function(request){console.log(''Response(#''+
request.id+''):''+JSON.stringify(request));};onUrlChangedThis
callbackisinvokedwhentheURLchanges,e.g.asitnavigatesaw
ayfromthecurrentURL.Theonlyargumenttothecallbackisthe
newtargetUrlstring.当url变化(比如它被导航离开当前页面的url时)调用此回调函数。传给回调函数的唯一参
数是新的targetURl字符串。ToretrievetheoldURL,usetheonLoadStartedc
allback.使用onLoadStarted回调函数以取回老的url。ExamplesvarwebPage=require
(''webpage'');varpage=webPage.create();page.onUrlChanged=funct
ion(targetUrl){console.log(''NewURL:''+targetUrl);};ChildPro
cessModuleThechild_processmoduleallowsyoutoinvokesubproce
ssesandcommunicatewiththemviastdin/stdout/stderr.This
isusefulfortaskssuchasprinting,sendingmail,orinvokings
criptsorprogramswritteninanotherlanguage(notJavascript).子
进程模块允许你调用子进程并且与之通过stdin/stdiout/stderr进行交流。这对于打印或者发送邮件的任务来说很有用。或
者调用其它语言编写的脚本或者程序。Tostartusing,youmustrequireareferenceto
thechild_processmodule:varprocess=require("child_process")va
rspawn=process.spawnvarexecFile=process.execFilevarchild=
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:",J
SON.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("execFile
STDERR:",JSON.stringify(stderr))})Spawnvarpage=require(''page
'').create();varspawn=require(''child_process'').spawn;page.open(
''http://google.com'',function(status){if(status==''success'')
{page.render(''/tmp/google-snapshot.jpg'');spawn(''/usr/bin/sensib
le-browser'',''file:///tmp/google-snapshot.jpg'');phantom.exit();
}})FileSystemModuleAsetofAPIfunctionsisavailabletoacces
sfilesanddirectories,modeledaftertheCommonJSFilesystempr
oposal.一租可以访问文件和目录的文件系统方案的函数,来自CommonJS。Tostartusing,youmust
requireareferencetothefsmodule:varfs=require(''fs'');Strea
mobjectsarereturnedfromthefs.openmethod.fs.open方法返回一个流对象。S
eparatorworkingDirectoryvarfs=require(''fs'');console.log(fs.wor
kingDirectory);//return"F:/liu/study/phantomjs/examples"(thedi
rectorythefileexsit)''absolute(string)''(string)Getstheabsolu
tepathtowherethephantomjsisbeenrunfrom.Ifyouuserelat
iveaddressesthenyoucangettheactualaddressofdirectories
aboveandbelowthephantomjsprogram.得到phantomjs运行的绝对路径。如果你使用相对路
径,那么你可以得到目录的实际路径varfs=require(''fs'');//Printthedirectoryfro
mwhichphantomjswasrun:varcwd=fs.absolute(".");console.log(
cwd);//Theparentdirectory:varparent=fs.absolute("../");cons
ole.log(parent);//Absolutepathofachilddirectory:varkid=f
s.absolute("/below");console.log(kid);changeWorkingDirectory(str
ing)(BOOL)ThisallowsyoutochangetheworkingDirectoryandret
urnstrueifthechangehappenedelsefalse改变工作目录,成功返回true,错误返回fa
lsevarfs=require(''fs'');console.log(fs.workingDirectory);//pri
ntsthelocationwherephantomjsisrunningfs.changeWorkingDirect
ory("C:\\");console.log(fs.workingDirectory);//printsC:/copy(st
ringsource,stringdestination)''Thiswilltrytocopyafilefro
monepathtoanother.这个函数尝试将一个文件拷贝到另外一个文件。Parameter1isthesou
rcefileandparameter2isthedestinationpathwiththefilena
me.参数1是源文件,参数2是带目标地址的文件名。Ifthesourcefilecan''tbefoundtheni
twillthrowa''UnabletocopyfileSOURCEatDESTINATION''andha
ngexecution.如果源文件无法被发现,将会抛出一个错误“无法复制文件到目的地”并且暂停执行。Ifthedestina
tioncannotbecreatedthenitwillthrowa''Unabletocopyfile
SOURCEatDESTINATION''andhangexecution.Itwillnotoverwrite
existingfiles.如果目的地文件无法被创建,将会抛出一个错误“无法复制文件到目的地”并且暂停执行。这个函数无法重写已
经存在的文件。varfs=require(''fs'');fs.copy("A.txt","folder/A.txt");co
pyTree(stringsource,stringdestination)Thiswilltrytocopya
directorytreefromonepathtoanother.这个函数将尝试拷贝一个目录结构到另外一个地方。P
arameter1isthesourcefoldertreeandparameter2isthedesti
nationpath.参数1是源文件树参数2是目的目录。Ifthedestinationfolderdoesn''tex
ist,itwillbecreated.Then,everyfileandfolderwillbecopi
edinthedestinationfolder.Folderswillberecursivelycopied.
如果目的文件夹不存在,其将被创建。每一个文件和每一个文件夹都会被拷贝到目的文件夹。文件夹会被递归地拷贝。Ifoneofthe
filesorfoldersfailstobecopiedorcreated,itwillthrowa
''UnabletocopydirectorytreeSOURCEatDESTINATION''andhangex
ecution.如果其中一个文件无法被拷贝或者创建,其将会抛出错误“UnabletocopydirectorytreeS
OURCEatDESTINATION”并且暂停执行。varfs=require(''fs'');fs.copyTree("s
ourceFolder/","destinationFolder/");phantom.exit();''exists(strin
g)''(BOOL)Thiswillreturntrueifthefileexists,otherwiseit
willreturnfalse.Thisfollowssymlinkstodeterminateifafile
exists.返回文件是否存在。存在true,否则false。varfs=require(''fs'');varpath=
''output.txt'';if(!fs.exists(path))fs.write(''HelloWorld'',path,
''w'');phantom.exit();varfs=require(''fs'');varpath=''/Full/Pat
h/To/test.txt'';if(fs.exists(path))console.log(''"''+path+''"exist
s.'');elseconsole.log(''"''+path+''"doesn\''texist.'');phantom.exit(
);''isAbsolute(string)''(BOOL)Thiswillreturntrueifthefilepa
thisabsolute,otherwiseitwillreturnfalseifthepathisrel
ative.如果文件路径是绝对路径返回true,否则返回falsevarfs=require(''fs'');varpath
=''/Full/Path/To/test.txt'';//isAbsolute(path)returnstrueifth
especifiedpathisanabsolutepath.if(fs.isAbsolute(path))con
sole.log(''"''+path+''"isanabsolutepath.'');elseconsole.log(''"''+
path+''"isNOTanabsolutepath.'');phantom.exit();isDirectory(str
ing)''(BOOL)varfs=require(''fs'');varpath="/etc/";//Getali
stallfilesindirectoryvarlist=fs.list(path);//Cyclethroug
hthelistfor(varx=0;xidn''tendpathwithaslash,youneedtodosohere.varfile=p
ath+list[x];if(fs.isDirectory(file)){//Dosomething}}phanto
m.exit();isExecutable(string)''(BOOL)varfs=require(''fs'');varp
ath=''/Full/Path/To/exec'';if(fs.isExecutable(path))console.log
(''"''+path+''"isexecutable.'');elseconsole.log(''"''+path+''"isNOT
executable.'');phantom.exit();''isFile(string)''(BOOL)varfs=req
uire(''fs'');varpath="/etc/";//Getalistallfilesindirector
yvarlist=fs.list(path);//Cyclethroughthelistfor(varx=0;
xash,youneedtodosohere.varfile=path+list[x];if(fs.isF
ile(file)){//Dosomething}}phantom.exit();''isLink(string)''(BO
OL)Thiswillreturntrueifthefilepathisasymlink(orashor
tcutonWindows),otherwiseitwillreturnfalse.判断是否是个symlink(或者
在windows下是个快捷方式)。BeawarethatUnix-likesystemsandWindowssyst
emsdon''tmanagesymlinksandshortcutsthesameway.注意unix类系统和wi
ndows系统有不同的方式。varfs=require(''fs'');varpath=''/Full/Path/To/fi
le'';if(fs.isLink(path))console.log(''"''+path+''"isalink.'');els
econsole.log(''"''+path+''"isanabsolutepath'');phantom.exit();''i
sReadable(string)''(BOOL)Thiswillreturntrueifthefileisrea
dable,otherwiseitwillreturnfalse.是否可读。Examplesvarfs=requi
re(''fs'');varpath=''/Full/Path/To/file'';if(fs.isReadable(path))
{console.log(''"''+path+''"isreadable.'');//Openthefilevaro
therFile=fs.open(path,{mode:''r''//Readmode});//Dosometh
ingwiththeopenedfile}elseconsole.log(''"''+path+''"isNOTread
able.'');phantom.exit();isWritable(string)''(BOOL)Thiswillreturn
trueifthefileiswritable,otherwiseitwillreturnfalse.是否可
写。varfs=require(''fs'');varpath=''/Full/Path/To/file'';if(fs.i
sWritable(path)){console.log(''"''+path+''"iswritable.'');varco
ntent=''HelloWorld!'';fs.write(path,content,''w'');}elseconsol
e.log(''"''+path+''"isNOTwritable.'');phantom.exit();list(string)''
(Array)Listthecontentsofadirectoryonthefilesystemassi
mplearray.Thiswillreturnsanemptyarrayifthedirectoryis
unreadableordoesn''texist.列出一个目录中的所有内容。如果目录无法访问或者不存在返回一个空数列。Exa
mples//EXAMPLE:Showalistoffilesinaspecificdirectoryas
afullyqualifiedpath:varfs=require(''fs'');varpath="/etc/";
//Getalistallfilesindirectoryvarlist=fs.list(path);//C
yclethroughthelistfor(varx=0;xe:Ifyoudidn''tendpathwithaslash,youneedtodosohere.v
arfile=path+list[x];if(fs.isFile(file)){//Dosomething}}
phantom.exit();''makeDirectory(string)''(BOOL)Createsadirectory
atthegivenpath.创造文件夹。成功true,失败false。如果已经存在文件夹,返回falseThiswill
returnstrueifthecreationwassuccessful,otherwisefalse.If
thedirectoryalreadyexists,itwillreturnsfalse.varfs=req
uire(''fs'');varpath=''/Full/Path/To/Test/'';if(fs.makeDirectory(t
est))console.log(''"''+path+''"wascreated.'');elseconsole.log(''"''
+path+''"isNOTcreated.'');phantom.exit();makeTree(string)''(BOOL
)Createsallnecessarydirectoriestobeabletocreatethedirec
tory.Thiswillreturnstrueifthecreationwassuccessful,other
wisefalse.Ifthedirectoryalreadyexists,itwillreturnstrue
.varfs=require(''fs'');varpath=''/Full/Path/To/Test/'';if(fs.ma
keDirectory(test))console.log(''"''+path+''"wascreated.'');elseco
nsole.log(''"''+path+''"isNOTcreated.'');phantom.exit();move(strin
gsource,stringdestination)''Thiswilltrytomoveafilefromo
nepathtoanother.移动文件。Parameter1isthesourcefileandparame
ter2isthedestinationpathwiththefilename.参数一为源文件,参数二位目标文件
地址。Ifthesourcefilecan''tbefoundthenitwillthrowa''Unable
tocopyfileSOURCEatDESTINATION''andhangexecution.Ifthede
stinationcannotbecreatedthenitwillthrowa''Unabletocopy
fileSOURCEatDESTINATION''andhangexecution.Itwillnotover
writeexistingfiles.Ifthesourcefilecannotbedeletedtheni
twillthrowa''UnabletodeletefileSOURCE''andhangexecutionv
arfs=require(''fs'');fs.move("A.txt","folder/A.txt");.''open(str
ingpath,string/Objectparameters)''(Stream)打开文件。Theparametero
bjectcancontain:mode:OpenMode.Astringmadeof''r'',''w'',''a
/+'',''b''characters.打开方式charset:AnIANA,caseinsensitive,char
setname.字符集名称Streamobjectsarereturnedfromthefs.openmethod
.Don''tforgettoclosethestream.Whenerrorsoccurduringacal
l,itwillthrowa''UnabletoopenfilePATH''andhangexecution.
varfs=require(''fs'');varfile=fs.open(''/path/to/file'',''r'');
//OpenMode.Astringmadeof''r'',''w'',''a/+'',''b''characters.var
otherFile=fs.open(''/path/to/otherFile'',{mode:''r''//(seeOpe
nModeabove)});varyetAnotherFile=fs.open(''/path/to/yetAnother
File'',{mode:''w'',//(seeOpenModeabove)charset:''US-ASCII''/
/AnIANA,caseinsensitive,charsetname.});file.close();otherFil
e.close();yetAnotherFile.close();''read(stringpath,string/Object
parameters)''(string)Theparameterobjectcancontain:mode:Ope
nMode.Astringmadeof''r'',''w'',''a/+'',''b''characters.charset
:AnIANA,caseinsensitive,charsetname.Opensthepathandretu
rnstheentirecontentsasastring.Whenerrorsoccurduringaca
ll,itwillthrowa''UnabletoopenfilePATH''andhangexecution
.Notethatthebehaviorofthismethodiscloselyrelatedtofs.o
pen.Examplesvarfs=require(''fs'');varcontent=fs.read(''file.tx
t'');console.log(''readdata:'',content);phantom.exit();''readLink(s
tring)''(string)Thiswillreturntheabsolutepathofafileorf
olderpointedbyasymlink(orshortcutonWindows).Ifthepath
isnotansymlinkorshortcut,itwillreturnanemptystring.返回一
个文件或者文件夹的软连接的绝对路径(在windows下是快捷方式)。如果路径不是一个软链接或者快捷方式,将返回一个空字符串var
fs=require(''fs'');varpath=''/Full/Path/To/test.txt'';if(fs.isL
ink(path)){varabsolute=fs.readLink(path);console.log(''Thea
bsolutepathof"''+path+''"is"''+absolute+''"'');}elseconsole.log(
''"''+path+''"isanabsolutepath'');phantom.exit();remove(string)''T
hiswilltrytodeletethespecifiedfile.删除指定文件Whenerrorsoccur
duringacall,itwillthrowa''UnabletoremovefilePATH''and
hangexecution.Examplesvarfs=require(''fs'');vartoDelete=''som
eFile.txt'';fs.removeDirectory(toDelete);phantom.exit();removeDire
ctory(string)''Thiswilltrytodeletethespecifiedfolder.删除文件夹T
hedirectoryneedstobeemptytoberemovedwiththismethod.To
deleteannonemptyfolder,fs.removeTreeshouldbeused.Whener
rorsoccurduringacall,itwillthrowa''Unabletoremovedirec
toryPATH''andhangexecution.Examplesvarfs=require(''fs'');var
toDelete=''someFolder'';//Testifthefolderisemptybeforedel
etingitif(fs.list(toDelete).length===0)fs.removeDirectory(toD
elete);phantom.exit();''removeTree(string)''删除树Thiswilltrytodel
eteeveryfileandfolderinthespecifiedfolderand,finally,d
eletethefolderitself.Whenerrorsoccurduringacall,itwill
throwa''UnabletoremovedirectorytreePATH''andhangexecution
.Examplesvarfs=require(''fs'');vartoDelete=''someFolder'';fs.ma
keDirectory(toDelete);fs.touch(toDelete+''/test.txt'');//Itwill
deletethe''someFolder''andthe''test.txt''initfs.removeDirecto
ry(toDelete);phantom.exit();size(string)''(int)Thiswillreturnt
hespecifiedfilesizeinbytes,ifitexists.返回指定文件的长度Whenerror
soccurduringacall,itwillthrowa''UnabletoreadfilePATH
size''andhangexecution.Examplesvarfs=require(''fs'');varpath
=''someFolder/'';//Gothrougheveryelementinthefolderfs.list(
path).forEach(function(file){file=path+file;//Removeever
yfilethatarelargerthan100bytesif(fs.isFile(file)&&fs.si
ze(file)>100)fs.remove(file);});phantom.exit();touch(string)''T
hiswilltrytocreateanemptyfileatthespecifiedpath.连接一个特殊
路径的空文件。Whenerrorsoccurduringacall,itwillthrowa''Unablet
oopenfilePATH''andhangexecution.Thecallwon''tthrowanerr
orifthefilealreadyexists.Notethatthebehaviorofthismeth
odiscloselyrelatedtofs.openandStream.write.Examplesvarfs
=require(''fs'');varpath=''test.txt'';//Createsanemptyfilefs.
touch(path);vartext=fs.read(path);//Ifthetest.txtdidn''tal
readyexist,thiswillprintanemptystringconsole.log(text);pha
ntom.exit();''write(stringsource,stringcontent,string/Objectp
arameters)''写入文件Theparameterobjectcancontain:mode:OpenMode.
Astringmadeof''r'',''w'',''a/+'',''b''characters.charset:AnIA
NA,caseinsensitive,charsetname.Ifthesourcefilecan''tbeop
enendthenitwillthrowa''UnabletoopenfileSOURCE''andhang
execution.Examplesvarfs=require(''fs'');varpath=''output.txt'';
varcontent=''HelloWorld!'';fs.write(path,content,''w'');phantom
.exit();SystemModuleTostartusing,youmustrequireareference
tothesystemmodule:varsystem=require(''system'');system.args
{String[]}Queriesandreturnsalistofthecommand-lineargument
s.Thefirstoneisalwaysthescriptname,whichisthenfollowe
dbythesubsequentarguments.查询并返回一个列表的命令行参数。第一个是脚本名称,其后是后续参数。Ex
amplesThefollowingexampleprintsallofthecommand-lineargume
nts:varsystem=require(''system'');varargs=system.args;if(arg
s.length===1){console.log(''Trytopasssomeargumentswheninvokingthisscript!'');}else{args.forEach(function(arg,i){console.log(i+'':''+arg);});}system.env{Object}Queriesandreturnsalistofkey-valuepairsrepresentingtheenvironmentvariables.查询并返回一个键-值对列表表示环境变量varsystem=require(''system'');varenv=system.env;Object.keys(env).forEach(function(key){console.log(key+''=''+env[key]);});OsRead-only.Anobjectprovidinginformationabouttheoperatingsystem,includingarchitecture,name,andversion.只读,一个提供有关操作系统的对象。包括系统位数,名称和版本。varsystem=require(''system'');varos=system.os;console.log(os.architecture);//''32bit''console.log(os.name);//''windows''console.log(os.version);//''7''system.pid{Number}Introduced:PhantomJS1.8Read-only.ThePID(ProcessID)forthecurrentlyexecutingPhantomJSprocess.1.8引入,只读。正在执行的phantomjs程序的PID(程序ID)system.platform{String}Read-only.Thenameoftheplatform,forwhichthevalueisalways''phantomjs''.只读。平台的名称,总是“phantomjs”varsystem=require(''system'');console.log(system.platform);//''phantomjs''WebServerModuleStability:EXPERIMENTAL稳定性:试验性质UsinganembeddedwebservermodulecalledMongoose,PhantomJSscriptcanstartawebserver.ThisisintendedforeaseofcommunicationbetweenPhantomJSscriptsandtheoutsideworldandisnotrecommendedforuseasageneralproductionserver.Thereiscurrentlyalimitof10concurrentrequests;anyotherrequestswillbequeuedup.通过使用一个名为“mongoose”嵌入的web服务模块,phantomJs脚本可以开启一个web服务器。这个是phantomjs脚本和外界进行交流的一种方式,但并不推荐用于一般的生产环境。目前有10个并发请求限制,其他任何请求都将排队。varwebserver=require(''webserver'');portTheportonwhichtheserverlistenrequests(readonly)服务端监听请求的端口号(只读。)CloseListenrequestargumentTherequestobjectpassedtothecallbackfunctionmaycontainthefollowingproperties:请求对象传递给回调函数可能包含以下属性:method:Definestherequestmethod(''GET'',''POST'',etc.)url:Thepathpartandquerystringpart(ifany)oftherequestURLhttpVersion:TheactualHTTPversionheaders:AlloftheHTTPheadersaskey-valuepairspost:Therequestbody(onlyfor''POST''and''PUT''methodrequests)postRaw:IftheContent-Typeheaderissetto''application/x-www-form-urlencoded''(thedefaultforformsubmissions),theoriginalcontentsofpostwillbestoredinthisextraproperty(postRaw)andthenpostwillbeautomaticallyupdatedwithaURL-decodedversionofthedata.如果Content-Typeheader设置成“application/x-www-form-urlencoded”(表单默认提交),原先提交的内容将被存在额外的属性(postRow)中,并且原先的post将会自动被包括URL-decoded版本的数据重写。responseargumentTheresponseobjectshouldbeusedtocreatetheresponseusingthefollowingpropertiesandfunctions:响应对象应该以以下属性和函数创建:headers:StoresallHTTPheadersaskey-valuepairs.ThesemustbesetBEFOREcallingwriteforthefirsttime.以键值对存放一切httpheader。必须在write被第一次使用之前设置。setHeader(name,value):setsaspecificheaderheader(name):returnsthevalueofthegivenheaderstatusCode:SetsthereturnedHTTPstatuscode.setEncoding(encoding):Indicatetheencodingtousetoconvertdatagiventowrite().BydefaultdatawillbeconvertedtoUTF-8.Indicate"binary"ifdataisabinarystring.write(data):Sendsachunkfortheresponsebody.Canbecalledmultipletimes.writeHead(statusCode,headers):Sendsaresponseheadertotherequest.Thestatuscodeisa3-digitHTTPstatuscode(e.g.404).Thelastargument,headers,aretheresponseheaders.Optionallyonecangiveahuman-readableheaderscollectionasthesecondargument.close():ClosestheHTTPconnection.Toavoidtheclientdetectingaconnectiondrop,remembertousewrite()atleastonce.Sendinganemptystring(i.e.response.write(''''))wouldbeenoughiftheonlyaimis,forexample,toreturnanHTTPstatuscodeof200("OK").为避免客户检测到一个链接中断,记得使用至少一次write()发送一个空字符串。这种情况适用于目标仅仅是返回一个http状态吗200的情况。closeGracefully():sameasclose(),butensuresresponseheadershavebeensentfirst(anddoatleastaresponse.write(''''))自动地在关闭前发送一个空字符串。
献花(0)
+1
(本文系莲颂首藏)