如何執行下載網頁(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參數調用url
和path
到phantomJS腳本system.args[1]
和system.args[2]
。任何想法如何做到這一點?
這是執行PhantomJS腳本的一種非常奇怪的方式。如果您使用Selenium的Java綁定,那麼您確實應該使用它的API。如果你想從Java調用一個普通PhantomJS腳本,然後調用PhantomJS二進制與腳本的子進程。請不要混用兩者,因爲當這變得更復雜時,你幾乎肯定會遇到問題。 –
你的意思是叫PhantomJS腳本像一個過程,而不是使用Ghostdriver的?我不太明白你在說什麼「你真的應該使用它的API」。我沒有這樣做嗎? – amarincolas
是的,我的意思是你應該使用'Runtime#exec'或類似的代碼,而不是通過Ghostdriver在腳本中執行相同的腳本。如果你不限於腳本,那麼你應該使用API,比如用'driver'打開一個頁面並獲取它的頁面源代碼。 –