【发布时间】:2015-11-21 19:28:53
【问题描述】:
我正在使用 CasperJS 从网站上抓取一些数据。在主页上,有一个包含所有 50 个州的列表的下拉列表。该值是 2 个字母的缩写。
var states;
casper.start(url);
casper.then(function() {
states = this.evaluate(function getOptionVals() {
// loop thru and get the values
return arrayValues;
});
});
接下来我想遍历缩写数组,然后在同一页面上填充一些元素。该页面上没有表单,只有一些单选按钮和一个提交按钮。
提交按钮导航到一个新的 .asp 页面,将搜索选项作为查询字符串参数传递。
casper.then(function () {
// loop over all states
this.eachThen(states,function(state) {
this.echo('state = ' + state.data);
// step 1
this.evaluate(function(state) {
console.log('In .evaluate the state is '+state);
// select the radio button
$('#searchoption1').prop('checked',true);
$('#searchoption2').prop('checked',false);
$('#showall').prop('checked',true);
// select the State from the dropdown
$('#state option[value="'+state+'"]').prop('selected', true);
$('#submit1').click();
},state.data); // pass in the array from the first casper.then call
// step 2
this.waitForSelector('table.mainTable tbody table tbody blockquote',function() {
this.evaluate(function(){
console.log($('table.mainTable h1 ').text());
});
});
})
});
casper.run();
我的问题是 CasperJS 的异步特性。当我运行它时,console.log() 报告每个通过循环的数组中第一个状态的结果。我已经为第 2 步尝试了一堆不同的方法(来自 SO 上的帖子),但无济于事。
如何让循环等到第 2 步完成后再继续?
输出如下所示:
start step #1 get state abbreviations
start #2 loop over all states
state = AL
In .evaluate the state is AL
loc: (/Find_Range/wts_subresults_test.asp)
dir2: (e)
Ranges for the State/Province of Alabama
state = AK
In .evaluate the state is AK
Ranges for the State/Province of Alabama
state = AZ
In .evaluate the state is AZ
Ranges for the State/Province of Alabama
state = AR
In .evaluate the state is AR
Ranges for the State/Province of Alabama
state = CA
In .evaluate the state is CA
Ranges for the State/Province of Alabama
state = CO
In .evaluate the state is CO
Ranges for the State/Province of Alabama
state = CT
In .evaluate the state is CT
Ranges for the State/Province of Alabama
所以this.waitForSelector 函数和this.evaluate 不是在浏览器上下文中“找到”正确的页面。我希望输出看起来像:
In .evaluate the state is AL
loc: (/Find_Range/wts_subresults_test.asp)
dir2: (e)
Ranges for the State/Province of Alabama
state = AK
In .evaluate the state is AK
Ranges for the State/Province of Alaska
state = AZ
In .evaluate the state is AZ
Ranges for the State/Province of Arizona
state = AR
In .evaluate the state is AR
Ranges for the State/Province of Arkansas
state = CA
In .evaluate the state is CA
Ranges for the State/Province of California
state = CO
In .evaluate the state is CO
Ranges for the State/Province of colorado
所以每次通过 this.each 后都应该在第 2 步之后导航回第一页。
【问题讨论】:
标签: javascript phantomjs casperjs