获取链接 URL
DOM 元素的属性和属性是有区别的。如果您有一个位于域http://example.com上的网站,并且您想href
在该页面上获取以下链接
<a href="/path/to/stuff">text</a>
如果你使用aElement.getAttribute("href")
,你会得到"/path/to/stuff"
,但如果你使用aElement.href
,你会得到计算出来的 URL "http://example.com/path/to/stuff"
。只有后者是 CasperJS(实际上是 PhantomJS)可以理解的 URL。
我告诉你这一点,因为casper.getElementsAttribute()
内部使用了element.getAttribute()
生成无法用casper.thenOpen()
.
修复很简单:
var urls = casper.evaluate(function(){
return [].map.call(document.querySelectorAll('a[href]'), function(a){
return a.href;
});
});
此外,您可能希望将casper.on()
事件注册移到呼叫上方casper.eachThen()
。您不需要在每次迭代中注册事件。
注册链接超时
由于您在某些 URL 未加载时遇到问题(可能是因为它们已损坏),您可以使用casper.options.stepTimeout
设置步骤超时,以便 CasperJS 不会在某些无法检索的 URL 上冻结。您还需要定义onStepTimeout()
回调,否则 CasperJS 将退出。
casper.then(function() {
var currentURL;
casper.options.stepTimeout = 10000; // 10 seconds
casper.options.onStepTimeout = function(timeout, stepNum){
this.echo('wait, this url timed out: ' + currentURL);
};
var urls = this.evaluate(function(){
return [].map.call(document.querySelectorAll('a[href]'), function(a){
return a.href;
});
});
this.on('http.status.404', function(resource) {
this.echo('wait, this url is 404: ' + resource.url);
});
urls.forEach(function(link) {
this.then(function(){
currentURL = link;
});
this.thenOpen(link, function(response) {
if (response == undefined || response.status >= 400) {
this.echo("failed: " + link);
}
});
});
});