|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- const sync=require("sync-request"); //同步
- var cheerio = require('cheerio'); //解析伪jquery语法
- let iconv = require('iconv-lite'); //转码
- let mysql = require('mysql');
- let config = {
- host : 'localhost',
- user : 'root',
- password : '111111',
- database : 'wp'
- };
- let pool = mysql.createPool(config);
- var arr=new Array();
- //构造图书信息
- url="http://www.kongfz.com/3/";
- var resp=sync("GET",url);
- html=iconv.decode(resp.body,"utf8");
- $ = cheerio.load(html);
- arr=new Array();
- items=$("div#listBox.result-list").find("div.item-info");
- $(items).each(function(index,elem){
- bookinfos=$(elem).find("div.zl-isbn-info");
- $(bookinfos).each((index3,elem3)=>{
- var lst=$(elem3).text().replace(/\s+|\n/gm," ").replace(/\//g,";").split(";");
- if(lst.length==4){
- let tmp=new Array();
- bookname=$(elem).find("div.title").eq(0).find("a").text();
- tmp.push(bookname);
- Array.prototype.push.apply(tmp,lst);
- arr.push(tmp);
- };
- });
- });
- //把图书信息写入数据库(此处用的是批量插入记录)
- sql2="INSERT INTO books (bookname,author,publisher,date,other) VALUES ?";
- pool.getConnection((err, connection) => {
- if (err) {
- console.error(err);
- }
- else
- {
- connection.query(sql2,[arr],(err, rows)=>{
- if (err) {
- console.error(err);
- }
- else
- {
- console.log("插入数据成功");
- };
- });
- };
- connection.release();
- });
复制代码
此时,数据库中数据是被批量增加的,通过查询数据库可以证明,但是控制台这里 不会退出 |
-
|