【问题标题】:How to pass arguments to a PhantomJS script from Selenium/Ghostdriver如何从 Selenium/Ghostdriver 将参数传递给 PhantomJS 脚本
【发布时间】: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 个参数调用 urlpath 到 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


【解决方案1】:

为什么不直接将参数传递给 executePhantomJS 方法?

driver.executePhantomJS(content, url, path);

【讨论】:

  • 使用您所说的在脚本中提供以下参数:main.js,--ip=,--port=36863,--logFile=phantomjsdriver.log,--logColor=false,--logLevel=INFO。没有 url arg 或路径 arg。
【解决方案2】:

我为解决问题所做的不是将 2 个参数作为参数传递(我们不在命令行中),而是将文件编辑为字符串并将这两个变量的值替换为 @ 987654321@.

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    相关资源
    最近更新 更多