我设置了一个全局变量
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());
});
});