我想使用 casperjs 检查网页中存在的所有损坏的链接。我编写了以下代码,但它不起作用:
casper.then(function() {
var urls=casper.getElementsAttribute('a[href]', 'href');
casper.eachThen(urls, function(response) {
var link=response.data;
this.thenOpen(demourl, function(response) {
if (response == undefined || response.status >= 400) {
this.echo("failed");
}
})
this.on('http.status.404', function(resource) {
this.echo('wait, this url is 404: ' + resource.url);
})
})
})
我的网页包含 400 多个链接。我的代码未完成执行,并且在某些链接后保持空闲状态。它没有给我任何回应。我不明白为什么会发生这种情况?
最佳答案
获取链接 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()
方法,该方法生成无法使用 打开的 URL 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);
}
});
});
});
关于javascript - 如何使用 Casperjs 检查网页中损坏的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31786354/