前端设计与开发—— 新闻爬虫及查询网站建立(2)
任务简介
主要的任务是首先通过爬虫收集数据,而后建立网站进行查询和分析,由于篇幅限制,这篇博客主要介绍爬虫的设置,选取澎湃新闻,网易新闻,新浪体育这三个网站进行爬取。
数据表准备
根据要求,我们建立以下结构的数据表用于存储爬取所得的数据:
CREATE TABLE news (
source_encoding VARCHAR(20),
title VARCHAR(300) NOT NULL,
author VARCHAR(30),
publish_date VARCHAR(50),
keywords VARCHAR(100),
description VARCHAR(2000),
content TEXT,
PRIMARY KEY (title)
)
模块引用
fs用于文件读写,myRequest用于进行http请求,cheerio主要是用来获取抓取到的页面元素和其中的数据信息。其中myIconv主要进行编码转换,由于爬取的是中文页面,而request不支持GBK格式的编码,因此如果网页是GBK格式的,用该模块iconv来完成转码工作。。
var fs = require('fs');
var myRequest = require('request')
var myCheerio = require('cheerio')
var myIconv = require('iconv-lite')
定义地址
###三个页面的地址
var seedURL = 'http://sports.sina.com.cn/'
var seedURL = 'https://www.thepaper.cn/'
var seedURL = 'https://news.163.com/';
获取种子页面
主要使用cheerio模块对html页面进行解析,并使用正则表达式进行url地址的规范化,筛选爬取的url。
request(seedURL, function(err, res, body) {
var html = myIconv.decode(body, myEncoding);
var $ = myCheerio.load(html, { decodeEntities: true });
var seedurl_news;
try {
seedurl_news = eval(seedURL_format);
} catch (e) { console.log('Url Error:' + e) };
seedurl_news.each(function(i, e) {
try {
var href = "";
href = $(e).attr("href");
if (href.toLowerCase().indexOf('http://') >= 0) myURL = href;
else if (href.toLowerCase().indexOf('https://') >= 0) myURL = href;
else if (href.startsWith('//')) myURL = 'http:' + href;
else myURL = seedURL.substr(0, seedURL.lastIndexOf('/') + 1) + href;
} catch (e) { console.log('Link Detection Error' + e) }
if (myURL.indexOf("doc-")== -1) return;
console.log(myURL);
newsGet(myURL);
});
});
读取新闻页面
在这一步我们解析新闻页面的内容,将其结构化存入数据库当中,我们依旧运用request,iconv-lite,cheerio解析获取信息。
function newsGet(myURL) { //读取新闻页面
request(myURL, function(err, res, body) {
if (body != undefined){
var html_news = myIconv.decode(body, myEncoding);
var $ = myCheerio.load(html_news, { decodeEntities: true });
myhtml = html_news;
console.log("转码读取成功:" + myURL);
var fetch = {};
## fetch储存了所有的字段信息
## 解析过程省略
}
}
}
在获取信息后,整合成SQL语句,连接Mysql进行插入:
const mysql=require('mysql')
const db=mysql.createPool({host:'localhost',port:'3306',user:'root',password:'root',database:'crawl'});
str=`'`+fetch.source_encoding+`'`+','+`'`+fetch.title+`'`+','+`'`+fetch.source_name+`'`+','+`'`+fetch.publish_date+`'`+','+`'`+fetch.keywords+`'`+','+`'`+fetch.desc+`'`+','+`'`+fetch.content+`'`
querystr='INSERT INTO news (source_encoding,title,author,publish_date,keywords,description,content) VALUE('+str+');'
实验结果
在运行爬虫后,在MySQL中进行查询,发现已经存储成功啦!