2016-01-20 124 views
0

如何執行下載網頁(args [1])的phantomJS腳本並將結果html保存到文件(args [2])中,如下所示:如何從Selenium/Ghostdriver將參數傳遞給PhantomJS腳本

var system = require('system'); 
var page = require('webpage').create(); 
var fs = require('fs'); 

// Set the url address and the path 
var url = system.args[1]; 
var path = system.args[2]; 

page.open(url, function() { 
    fs.write(path, page.content, 'w'); 
    phantom.exit(); 
}); 

我使用selenium/ghostdriver如下執行腳本:

DesiredCapabilities cap = new DesiredCapabilities(); 
cap.setJavascriptEnabled(true); 
cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,".../phantomjs"); 

String [] phantomJsArgs = {url,path}; 
cap.setCapability(PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_CLI_ARGS, phantomJsArgs); 

PhantomJSDriver driver = new PhantomJSDriver(cap);   
String content = new String(Files.readAllBytes(Paths.get(scriptPath)),Charset.forName("UTF-8")); 
driver.executePhantomJS(content); 

此代碼的工作除了當我試圖通過從selenium/ghostdriver 2參數調用urlpath到phantomJS腳本system.args[1]system.args[2]。任何想法如何做到這一點?

+0

這是執行PhantomJS腳本的一種非常奇怪的方式。如果您使用Selenium的Java綁定,那麼您確實應該使用它的API。如果你想從Java調用一個普通PhantomJS腳本,然後調用PhantomJS二進制與腳本的子進程。請不要混用兩者,因爲當這變得更復雜時,你幾乎肯定會遇到問題。 –

+0

你的意思是叫PhantomJS腳本像一個過程,而不是使用Ghostdriver的?我不太明白你在說什麼「你真的應該使用它的API」。我沒有這樣做嗎? – amarincolas

+1

是的,我的意思是你應該使用'Runtime#exec'或類似的代碼,而不是通過Ghostdriver在腳本中執行相同的腳本。如果你不限於腳本,那麼你應該使用API​​,比如用'driver'打開一個頁面並獲取它的頁面源代碼。 –

回答

1

爲什麼不只是傳遞參數給executePhantomJS方法?

driver.executePhantomJS(content, url, path); 
+0

使用你說的在腳本中給出以下參數:'main.js, - ip =, - port = 36863, - logFile = phantomjsdriver.log, - logColor = false, - logLevel = INFO'。沒有url arg或路徑arg。 – amarincolas

0

我做了什麼來解決這個問題是不是傳遞了2個參數作爲自變量(我們不是在命令行)的,我所做的是編輯文件作爲一個字符串,並取代那些值兩個變量與String.replace()