【发布时间】:2016-01-20 07:43:24
【问题描述】:
我如何执行phantomJS 脚本,该脚本下载网页(args[1])并将结果 html 保存到文件(args[2])中,如下所示:
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”。我不是已经这样做了吗?
-
是的,我的意思是你应该使用
Runtime#exec或类似的,而不是当你有一个脚本时通过Ghostdriver执行相同的脚本。如果您不限于脚本,那么您应该使用 API,例如使用driver打开页面并获取它的页面源。
标签: java selenium selenium-webdriver phantomjs ghostdriver