前端设计与开发——1

首先按照示例尝试

 

1.首先定义需要的包

var fs = require('fs');
var myRequest = require('request')
var myCheerio = require('cheerio')//获取element内容
var myIconv = require('iconv-lite')//转码
require('date-utils');//解析日期

2.定义所爬取的种子界面

var source_name = "中国新闻网";
var domain = 'http://www.chinanews.com/';
var myEncoding = "utf-8";
var seedURL = 'http://www.chinanews.com/';

3.定义新闻页面具体元素读取方法,如date_formate在网页中是按照span id="pubtime_baidu"存储

var seedURL_format = "$('a')";//需要取出所有a的链接
var keywords_format = " $('meta[name=\"keywords\"]').eq(0).attr(\"content\")";//从header里面把keywords拿出来放到里面去,<meta name="keywords" content="。。。">
var title_format = "$('title').text()";
var date_format = "$('#pubtime_baidu').text()";//<span id="pubtime_baidu">2020-05-07 09:48:53</span>
var author_format = "$('#editor_baidu').text()";//<span id="editor_baidu">责任编辑:陈海峰</span>
var content_format = "$('.left_zw').text()";//<div class="left_zw"> 
​
var desc_format = " $('meta[name=\"description\"]').eq(0).attr(\"content\")";
var source_format = "$('#source_baidu').text()";
var url_reg = /\/(\d{4})\/(\d{2})-(\d{2})\/(\d{7}).shtml/;
var regExp = /((\d{4}|\d{2})(\-|\/|\.)\d{1,2}\3\d{1,2})|(\d{4}年\d{1,2}月\d{1,2}日)/
​
var fs = require('fs');
var myRequest = require('request')
var myCheerio = require('cheerio')//获取element内容
var myIconv = require('iconv-lite')//转码
require('date-utils');//解析日期

4.模仿浏览器request

4.1 request需要模伪装成仿浏览器,防止被屏蔽

//user-agent:显示是什么浏览器
var headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'
}
​
//request模块异步fetch url
function request(url, callback) {
    var options = {
        url: url,
        encoding: null,
        //proxy: 'http://x.x.x.x:8080',//过代理
        headers: headers,
        timeout: 10000 //
    }
    myRequest(options, callback)
}

4.2 读取种子页面,并爬取种子页面下的所有网页

request(seedURL, function(err, res, body) { //读取种子页面
    // try {
    //用iconv转换编码
    var html = myIconv.decode(body, myEncoding);
    //console.log(html);
    //准备用cheerio解析html
    var $ = myCheerio.load(html, { decodeEntities: true });
    // } catch (e) { console.log('读种子页面并转码出错:' + e) };
​
    var seedurl_news;
​
    try {
        seedurl_news = eval(seedURL_format);//取出所有a——href的链接
        //console.log(seedurl_news);
    } catch (e) { console.log('url列表所处的html块识别出错:' + e) };
​
    seedurl_news.each(function(i, e) { //遍历种子页面里所有的a链接
        var myURL = "";
        try {
            //得到具体新闻url
            var href = "";
            href = $(e).attr("href");
            if (href.toLowerCase().indexOf('http://') >= 0) myURL = href; //http://开头的 绝对路径方式
            else if (href.startsWith('//')) myURL = 'http:' + href; 开头的 相对路径 需要转换成绝对路径
            else myURL = seedURL.substr(0, seedURL.lastIndexOf('/') + 1) + href; //其他
​
        } catch (e) { console.log('识别种子页面中的新闻链接出错:' + e) }
​
        if (!url_reg.test(myURL)) return; //检验是否符合新闻url的正则表达式,符合就用newsget读取
        //console.log(myURL);
        newsGet(myURL); //读取新闻页面
    });
});

4.3 读取页面并进行格式化存储成js文件

function newsGet(myURL) { //读取新闻页面
    request(myURL, function(err, res, body) { //读取新闻页面
        //try {
        var html_news = myIconv.decode(body, myEncoding); //用iconv转换编码
        //console.log(html_news);
        //准备用cheerio解析html_news
        var $ = myCheerio.load(html_news, { decodeEntities: true });
        myhtml = html_news;
        //} catch (e) {    console.log('读新闻页面并转码出错:' + e);};
​
        console.log("转码读取成功:" + myURL);
​
        //动态执行format字符串,构建json对象准备写入文件或数据库
        var fetch = {};//构造空的fetch对象,用来存title、content、url等等
        fetch.title = "";
        fetch.content = "";
        fetch.publish_date = (new Date()).toFormat("YYYY-MM-DD");
        //fetch.html = myhtml;
        fetch.url = myURL;
        fetch.source_name = source_name;
        fetch.source_encoding = myEncoding; //编码
        fetch.crawltime = new Date();//爬取时间
​
        if (keywords_format == "") fetch.keywords = source_name; // eval(keywords_format);  //没有关键词就用sourcename
        else fetch.keywords = eval(keywords_format);
​
        if (title_format == "") fetch.title = ""
        else fetch.title = eval(title_format); //标题
​
        if (date_format != "") fetch.publish_date = eval(date_format); //刊登日期   
        console.log('date: ' + fetch.publish_date);
        fetch.publish_date = regExp.exec(fetch.publish_date)[0];
        fetch.publish_date = fetch.publish_date.replace('年', '-')
        fetch.publish_date = fetch.publish_date.replace('月', '-')
        fetch.publish_date = fetch.publish_date.replace('日', '')
        fetch.publish_date = new Date(fetch.publish_date).toFormat("YYYY-MM-DD");
​
        if (author_format == "") fetch.author = source_name; //eval(author_format);  //作者
        else fetch.author = eval(author_format);
​
        if (content_format == "") fetch.content = "";
        else fetch.content = eval(content_format).replace("\r\n" + fetch.author, ""); //内容,是否要去掉作者信息自行决定
​
        if (source_format == "") fetch.source = fetch.source_name;
        else fetch.source = eval(source_format).replace("\r\n", ""); //来源
​
        if (desc_format == "") fetch.desc = fetch.title;
        else fetch.desc = eval(desc_format).replace("\r\n", ""); //摘要    
​
        
        var filename = source_name + "_" + (new Date()).toFormat("YYYY-MM-DD") +
            "_" + myURL.substr(myURL.lastIndexOf('/') + 1) + ".json";
        存储json
        fs.writeFileSync(filename, JSON.stringify(fetch));
    });
}

 

最终结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值