[英]simple scraper application on node.js / jquery
我正在尝试使用 jQuery 在 Node.js 上构建一个小型应用程序,它将在提供的位置请求内容。 如果 URL 指向非 HTML 的资源,它将输出返回的内容类型。 否则,它将读取 HTML 数据并输出页面的标题和描述,然后是页面上可点击的链接列表。 这是我的代码:
var request = require('request'),
jsdom = require('jsdom'),
fs = require('fs'),
colors = require('colors'),
argv = require('optimist').argv;
colors.setTheme({ c1: 'blue', c2: 'red', c3: 'inverse' });
var myFunc = function( link, cb ){
console.log( 'requesting page: '.c3 + link.c3 );
// Step 1 - request to the page
request({
uri: link,
}, function (err, response, body) {
// Handle response issues
if ( err || response.statusCode !== 200 ) {
if ( !response ){
console.log( 'Ooops! page doesn`t exist or wrong URL format'.c2 )
} else {
console.log('error: '+ response.statusCode )
}
cb();
} else {
console.log( 'response code: ' + response.statusCode )
// Step 2 - invoking jsdom and jQuery
jsdom.env({
html: body,
src: [
fs.readFileSync(__dirname + "/lib/jquery-1.9.1.min.js").toString()
],
done: function(err, window) {
if(err) {
cb();
} else {
var $ = window.$;
// Step 3, final part - parse content with jQuery selectors
console.log( '\nThis page is:\n'.c1 + $(body)[0]._ownerDocument._contentType )
console.log( '\nPage title: \n'.c1 + $('title').text().trim() );
console.log( $('head meta[name="description"]').attr('content') !== undefined ? '\nPage description: \n'.c1 + $('head meta[name="description"]').attr('content') + '\n' : '\nPage description: \n'.c1 + 'No description on the page\n'.c2);
console.log( '\nClickable links on the page: \n'.c1 )
$('a').each(function(){
if ( $(this).attr('href') !== undefined ){
console.log( $(this).attr('href').slice(0, 4) == 'http' ? $(this).attr('href') : link + $(this).attr('href'))
}
});
cb();
}
}
})
}
}
);
};
因此,它完美地刮的HTML页面,但我不知道如何实现这部分
如果 URL 指向非 HTML 的资源,它将输出返回的内容类型。
请分享一个如何做这部分的想法。 提前致谢!
我从来没有使用过 JQuery,我是 javascript 的初学者,但我会做的是获取字符串中的 url,删除所有内容直到最后一个点(例如:“ http://www.web.com/content.php " => "php"),将其与 'html' 进行比较,并打印出来,因为它将是内容类型。
编辑:
//url is a string
function validate (url) {
//Get whatever is after the last dot in the url
//Compare to html
//Return true if it is equals, or false if not
return (url.substr(url.lastIndexOf('.')) === 'html');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.