为什么我得到第一个数组项是未定义的?
Why i get the first array item is undefined?
我设置了一个全局变量
var URL = [];
并获取数据:
casper.then(function () {
// I get 19 links from this code
URL = this.evaluate(getURL);
// I can see i get the first link
console.log(URL[0] + '***************');
});
但是在这个函数之后我的 URL[0] 显示未定义。
// But this URL[0] shows the error that
casper.thenOpen("'" + URL[0] + "'", function () {
this.echo(this.getTitle());
});
这样的错误:
[debug] [phantom] opening url: 'undefined', HTTP GET
[debug] [phantom] Navigation requested: url=file:///Users/motogod19/PhantomPractice/parse_movie/'undefined', type=Other, willNavigate=true, isMainFrame=true
[warning] [phantom] Loading resource failed with status=fail: file:///Users/motogod19/PhantomPractice/parse_movie/'undefined'
为什么?我想不通。有任何想法吗 ?提前致谢。
您调用了一个 async
方法。因此,您需要确保在调用需要此变量值的下一个方法之前先获取 URL
的值。试试这个:
casper.then(function () {
// I get 19 links from this code
URL = this.evaluate(getURL);
// I can see i get the first link
console.log(URL[0] + '***************');
if (!URL[0]) {
// should handle the condition where url list is empty
return;
}
casper.thenOpen("'" + URL[0] + "'", function () {
this.echo(this.getTitle());
});
});
我设置了一个全局变量
var URL = [];
并获取数据:
casper.then(function () {
// I get 19 links from this code
URL = this.evaluate(getURL);
// I can see i get the first link
console.log(URL[0] + '***************');
});
但是在这个函数之后我的 URL[0] 显示未定义。
// But this URL[0] shows the error that
casper.thenOpen("'" + URL[0] + "'", function () {
this.echo(this.getTitle());
});
这样的错误:
[debug] [phantom] opening url: 'undefined', HTTP GET
[debug] [phantom] Navigation requested: url=file:///Users/motogod19/PhantomPractice/parse_movie/'undefined', type=Other, willNavigate=true, isMainFrame=true
[warning] [phantom] Loading resource failed with status=fail: file:///Users/motogod19/PhantomPractice/parse_movie/'undefined'
为什么?我想不通。有任何想法吗 ?提前致谢。
您调用了一个 async
方法。因此,您需要确保在调用需要此变量值的下一个方法之前先获取 URL
的值。试试这个:
casper.then(function () {
// I get 19 links from this code
URL = this.evaluate(getURL);
// I can see i get the first link
console.log(URL[0] + '***************');
if (!URL[0]) {
// should handle the condition where url list is empty
return;
}
casper.thenOpen("'" + URL[0] + "'", function () {
this.echo(this.getTitle());
});
});