【发布时间】:2018-03-10 23:30:12
【问题描述】:
在我用于负载测试的 phantomJS 脚本中使用 webpage API 时遇到一些问题。
我在子进程中运行脚本,如下所示:
var path = require('path');
var childProcess = require('child_process');
var binPath = require('phantomjs').path;
var childArgs = [
path.join(__dirname, 'phantom-script.js')
];
var spawn = childProcess.spawn;
var child = spawn(binPath, childArgs);
child.stdout.on('data', function(data) {
const buf = Buffer.from(data);
console.log('stdout:', buf.toString());
});
child.stderr.on('data', function(data) {
const buf = Buffer.from(data);
console.log('stderr:', buf.toString());
});
还有我的简单 phantomJS 脚本:
var webPage = require('webpage');
var page = webPage.create();
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.onResourceError = function(resourceError) {
console.log(resourceError.errorCode + ':', resourceError.errorString);
};
function runScript() {
page.open('<webpage-url>', function(status) {
console.log('Status:', status);
if (status === 'success') {
page.evaluate(function() {
console.log('Title:', document.title);
});
}
});
}
runScript();
所以要启动 phantomJS 脚本,如果这两个文件都在 test/ 目录中,并且我的当前目录是其中之一:node test/child-process.js,然后生成子进程并运行我的 phantomJS 脚本。
因此,这使脚本运行,但由于资源错误,它总是在page.open 中失败。将我的网址替换为 Google 或任何网站都可以正常工作。
onResourceError 记录的错误是stdout: 202: Cannot open file:///Users/<user>/path/to/local/current/directory: Path is a directory。
这始终是我运行此脚本的路径。如果我将一个目录下移到test/ 并使用node child-process.js 运行它,则错误会记录该目录。
作为一个无头浏览器,我假设 phantomJS 会像任何客户端一样与网页交互,只是不渲染模板——运行脚本的当前目录与打开网页有什么关系?为什么当网页 URL 指向公共网站时,它会尝试从我的本地目录加载资源,该网站托管在 page.open 的第一个参数中指定的 IP 和 PORT(例如 xx.xxx.xx.xx:PORT)?
我在这里有点不知所措。 phantomJS 路径和所有内容都是正确的,因为它可以正常运行脚本。我只是不明白为什么page.open 会尝试打开调用脚本的目录——这与它的功能有什么关系,即打开 URL 并将其加载到页面?
【问题讨论】: