Commit 90933a4e by 马玮

Save clues into db

parent f8dc84f4
...@@ -16,24 +16,28 @@ sudo yum install redis ...@@ -16,24 +16,28 @@ sudo yum install redis
``` ```
## To do list: ## To do list:
- [x] 使用ES7语法重构代码 - [x] 功能:根据环境变量读取配置
- [x] 根据环境变量读取配置 - [x] 功能:集成若快验证码识别
- [x] 集成若快验证码识别 - [x] 功能:cookie持久化,保存到redis或者db
- [x] tryLogin与login - [x] 功能:login(表单登录)与tryLogin(使用已存储cookie登录)
- [x] cookie保存到redis持久化 - [x] 功能:抓取三天内线索信息并输出
- [x] 抓取三天内线索信息并输出 - [x] 功能:每次抓取增加随机间隔
- [x] 每次抓取增加随机间隔 - [x] 功能:捕获程序错误及异常
- [x] 捕获程序错误及异常 - [ ] 功能:线索入库
- [ ] 汽车之家发起request前先获取接口链接,通过url解析修改参数获取正确接口以保证稳定性 - [ ] 功能:线索入库前对数据进行基础校验,所有字段入库前检查去空格
- [ ] 每次tryLogin刷新验证码 - [ ] 功能:Cluster分布式进程调度
- [ ] login失败重试三次机制 - [ ] 功能:增加日志系统
- [ ] waitForNextPage有时会超时,增加wait重试机制 - [ ] 功能:增加随机userAgent
- [ ] 创建Spider基类复用代码(setCookies|getCookies|getHeaderCookies) - [ ] 功能:增加测试用例和工具
- [ ] debug文件加入.gitignore - [ ] 优化:整理所有错误,建立错误继承关系,区分操作错误和程序错误
- [ ] 线索入库 - [ ] 优化:易车抓取方式尝试破解request,phantomjs方案有点过于缓慢
- [ ] Cluster分布式进程调度 - [ ] 优化:汽车之家发起request前先获取接口链接,通过url解析修改参数获取正确接口以保证稳定性
- [ ] 增加日志系统 - [ ] 优化:每次tryLogin刷新验证码
- [ ] 增加随机userAgent - [ ] 优化:login失败重试三次机制
- [ ] 使用import|export写法增加模块读取速度 - [ ] 优化:waitForNextPage有时会超时,增加wait重试机制
- [ ] 增加测试用例和工具 - [ ] 优化:完善.gitignore
- [ ] 补充.gitignore忽略测试文件 - [ ] 优化:进程Graceful Stop
- [ ] 优化:统一所有代码let和const的使用风格
- [x] 重构:使用ES7语法重构代码
- [ ] 重构:创建Spider基类复用代码(setCookies|getCookies|getHeaderCookies)
- [ ] 重构:使用import|export写法增加模块读取速度
...@@ -11,16 +11,18 @@ const Spider = require('./lib/spider'); ...@@ -11,16 +11,18 @@ const Spider = require('./lib/spider');
program program
.version('0.1.0') .version('0.1.0')
.option('-w, --webname <website name>', 'Add website we want fetch') .option('-u, --userid <user id>', 'Assign our user id')
.option('-t, --task <task name>', 'Add task we want to execute') .option('-t, --task <task name>', 'Add task we want to execute')
.option('-w, --webname <website name>', 'Add website we want fetch')
.parse(process.argv); .parse(process.argv);
// console.log(process.pid); // console.log(process.pid);
const dealerWebInfo = config.get(program.webname); const dealerWebInfo = config.get(program.webname);
const spider = new Spider({ const spider = new Spider({
username : dealerWebInfo.USERNAME, userid : program.userid,
password : dealerWebInfo.PASSWORD, task : program.task,
webname : program.webname, webname : program.webname,
task : program.task username : dealerWebInfo.USERNAME,
password : dealerWebInfo.PASSWORD
}); });
spider.execute(); spider.execute();
\ No newline at end of file
...@@ -30,3 +30,10 @@ SOFTKEY = "b167ed636a224990a2f04ae2d28d1542" ...@@ -30,3 +30,10 @@ SOFTKEY = "b167ed636a224990a2f04ae2d28d1542"
FOUR_LETTERS = 2040 # 四个英文字母 FOUR_LETTERS = 2040 # 四个英文字母
FOUR_CHARACTERS = 3040 # 四个字母数字混合 FOUR_CHARACTERS = 3040 # 四个字母数字混合
ARITHMETIC = 7100 # 算术题 ARITHMETIC = 7100 # 算术题
[DB.MASTER]
HOST = 'localhost'
PORT = 3306
USER = 'root'
PASSWORD = 'root'
DATABASE = 'test'
process.env.NODE_CONFIG_DIR = '../../config';
const config = require('config');
const mysql = require('mysql2');
const clusterConfig = {
removeNodeErrorCount: 5,
defaultSelector: 'RR'
};
const poolCluster = mysql.createPoolCluster(clusterConfig);
const db = config.get('DB');
for (let [nodeId, nodeConfig] of Object.entries(db)) {
console.log(nodeConfig);
poolCluster.add(nodeId, {
host: nodeConfig.HOST,
port: nodeConfig.PORT,
user: nodeConfig.USER,
password: nodeConfig.PASSWORD,
database: nodeConfig.DATABASE
});
}
module.exports = poolCluster;
poolCluster.getConnection('MASTER', function (err, connection) {
connection.query(
'SELECT * FROM `test` WHERE `id` > 1',
function(err, results, fields) {
console.log(results); // results contains rows returned by server
// console.log(fields); // fields contains extra meta data about results, if available
}
);
});
// process.env.NODE_CONFIG_DIR = '../../config';
const config = require('config');
const mysql = require('mysql2');
const clusterConfig = {
removeNodeErrorCount: 5,
defaultSelector: 'RR'
};
const poolCluster = mysql.createPoolCluster(clusterConfig);
const db = config.get('DB');
for (let [nodeId, nodeConfig] of Object.entries(db)) {
console.log(nodeConfig);
poolCluster.add(nodeId, {
host: nodeConfig.HOST,
port: nodeConfig.PORT,
user: nodeConfig.USER,
password: nodeConfig.PASSWORD,
database: nodeConfig.DATABASE
});
}
module.exports = poolCluster;
const errors = require('../errors');
const moment = require('moment');
const poolCluster = require('../database/poolCluster');
class DealerHelper {
// 保存线索
static async saveClues(params) {
const userid = params.userid || 0;
const clues = params.clues || [];
const webname = params.webname || '';
if (!userid || !clues.length || !webname) {
throw errors.AppError('Params missing');
}
poolCluster.getConnection('MASTER', function (err, connection) {
const updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
const valuesSql = [];
const _clue = {
customerName: '',
customerPhone: '',
customerArea: '',
licenseArea: '',
expectCar: '',
salesName: '',
salesPhone: '',
createdAt: '0000-00-00 00:00:00',
};
for (let clue of clues) {
clue = Object.assign(_clue, clue);
let valueSql = '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
let inserts = [userid, params.webname,
clue.customerName, clue.customerPhone, clue.licenseArea, clue.expectCar,
clue.salesName, clue.salesPhone, clue.createdAt, updated_at];
valueSql = connection.format(valueSql, inserts);
valuesSql.push(valueSql);
}
const sql = `INSERT INTO clue (
userid, webname, customer_name, customer_phone, license_area, expect_car,
sales_name, sales_phone, created_at, updated_at
) VALUES ${valuesSql.join(',')} ON DUPLICATE KEY UPDATE updated_at = VALUES(updated_at)`;
console.log(sql);
connection.query(
sql,
function(err, results, fields) {
connection.release();
if (err) {
throw err;
}
if (results.affectedRows) {
console.log('线索保存成功!');
return true;
} else {
console.log('线索保存失败!');
return false;
}
}
);
});
}
}
module.exports = DealerHelper;
\ No newline at end of file
...@@ -13,6 +13,7 @@ const axios = require('axios'); ...@@ -13,6 +13,7 @@ const axios = require('axios');
// 自定义模块 // 自定义模块
const captcha = require('../../captcha'); const captcha = require('../../captcha');
const errors = require('../../errors'); const errors = require('../../errors');
const DealerHelper = require('../../helpers/Dealer');
Promise.promisifyAll(redis); Promise.promisifyAll(redis);
Promise.promisifyAll(fs); Promise.promisifyAll(fs);
...@@ -39,21 +40,20 @@ class AutoHome { ...@@ -39,21 +40,20 @@ class AutoHome {
} }
async execute() { async execute() {
return new Promise((resolve, reject) => { switch (this.params.task) {
switch (this.params.task) { case 'login': {
case 'login': { await this.login();
this.login(); return;
break; }
} case 'tryLogin': {
case 'tryLogin': { await this.tryLogin();
return this.tryLogin(); return;
}
case 'fetchClues': {
this.fetchClues();
break;
}
} }
}); case 'fetchClues': {
await this.fetchClues();
return;
}
}
} }
async tryLogin() { async tryLogin() {
...@@ -247,34 +247,67 @@ class AutoHome { ...@@ -247,34 +247,67 @@ class AutoHome {
Cookie: cookieStr Cookie: cookieStr
} }
}).then(async res => { }).then(async res => {
const clues = res.data; const clueData = res.data;
const writeStream = fs.createWriteStream('res.html'); const writeStream = fs.createWriteStream('res.html');
writeStream.write(JSON.stringify(res.data)); writeStream.write(JSON.stringify(res.data));
if (!rowcount) { if (!rowcount) {
rowcount = clues.result.rowcount; rowcount = clueData.result.rowcount;
console.log('只进入一次总数:', rowcount); console.log('只进入一次总数:', rowcount);
} }
for (let clue of clues.result.list) { const clues = [];
for (let l of clueData.result.list) {
const clue = {};
customerIndex++; customerIndex++;
let $ = cheerio.load(clue.CustomerNameStr); // 名字字符串样本:<a href='#' onclick='showCusDetailWithId("303590")'>田华</a><br/><span></span>
let idMatch = $.html().match(/showCusDetailWithId\(&quot;(\d*)&quot;\)/); const idMatch = l.CustomerNameStr.match(/showCusDetailWithId\("(\d+)"\)/) || [];
// 手机地区字符串样本:13253979998<br/>河南 三门峡
// 备用分割方案:const phoneAreaMatch = l.CustomerPhoneStr.split('<br/>') || [];
const phoneAreaMatch = l.CustomerPhoneStr.match(/(\d*)\<br\/\>((\S+)\s(\S+))?/) || [];
// 田淮蒲 18300683353
const salesMatch = l.SalesNameStr.match(/(\S+)\s(\d+)/);
clue.customerId = idMatch[1] || 0;
clue.customerName = (cheerio.load(l.CustomerNameStr).text() || '').trim();
clue.customerPhone = (phoneAreaMatch[1] || '').trim();
clue.customerArea = (phoneAreaMatch[2] || '').trim();
clue.salesName = (salesMatch[1] || '').trim();
clue.salesPhone = (salesMatch[2] || '').trim();
clue.orderType = l.OrderTypeStr.trim();
clue.orderState = l.OrderStateStr.trim();
clue.licenseArea = l.LicenseCityStr.trim();
clue.expectCar = l.SpecNameStr.trim();
clue.createdAt = l.LeadTimeStr.trim();
clues.push(clue);
clue.CustomerId = idMatch[1] || 0;
console.log('客户序号:', customerIndex); console.log('客户序号:', customerIndex);
console.log('客户ID:', clue.CustomerId); console.log('客户ID:', clue.customerId);
console.log('客户姓名:', $.text()); console.log('客户姓名:', clue.customerName);
console.log('客户号码:', clue.CustomerPhoneStr); console.log('客户号码:', clue.customerPhone);
console.log('负责销售:', clue.SalesNameStr); console.log('客户地区:', clue.customerArea);
console.log('线索类型:', clue.OrderTypeStr); console.log('负责销售:', clue.salesName);
console.log('线索状态:', clue.OrderStateStr); console.log('销售号码:', clue.salesPhone);
console.log('线索获得时间:', clue.LeadTimeStr); console.log('线索获得时间:', clue.createdAt);
console.log('上牌地区:', clue.LicenseCityStr); console.log('上牌地区:', clue.licenseArea);
console.log('线索意向车型:', clue.SpecNameStr); console.log('线索意向车型:', clue.expectCar);
// TODO: just for debug, remove them later
console.log('线索类型:', clue.orderType);
console.log('线索状态:', clue.orderState);
console.log('==========================================================================='); console.log('===========================================================================');
} }
if (this.params.userid) {
await DealerHelper.saveClues({
clues: clues,
userid: this.params.userid,
webname: this.params.webname
});
}
// 判断是否抓取完全
if (customerIndex < rowcount) { if (customerIndex < rowcount) {
let randomSecs = randomInt(1, 8); let randomSecs = randomInt(1, 8);
console.log(`随机等待${randomSecs}秒`); console.log(`随机等待${randomSecs}秒`);
...@@ -285,7 +318,8 @@ class AutoHome { ...@@ -285,7 +318,8 @@ class AutoHome {
} }
}); });
} }
fetchByPage(params.pageindex); await fetchByPage();
return;
} catch (e) { } catch (e) {
console.dir(e.stack); console.dir(e.stack);
// throw e; // throw e;
...@@ -293,4 +327,4 @@ class AutoHome { ...@@ -293,4 +327,4 @@ class AutoHome {
} }
} }
module.exports = AutoHome; module.exports = AutoHome;
\ No newline at end of file
...@@ -13,6 +13,7 @@ const axios = require('axios'); ...@@ -13,6 +13,7 @@ const axios = require('axios');
// 自定义模块 // 自定义模块
const captcha = require('../../captcha'); const captcha = require('../../captcha');
const errors = require('../../errors'); const errors = require('../../errors');
const DealerHelper = require('../../helpers/Dealer');
Promise.promisifyAll(redis); Promise.promisifyAll(redis);
Promise.promisifyAll(fs); Promise.promisifyAll(fs);
...@@ -39,21 +40,20 @@ class EasyPass { ...@@ -39,21 +40,20 @@ class EasyPass {
} }
async execute() { async execute() {
return new Promise((resolve, reject) => { switch (this.params.task) {
switch (this.params.task) { case 'login': {
case 'login': { await this.login();
this.login(); return;
break; }
} case 'tryLogin': {
case 'tryLogin': { await this.tryLogin();
return this.tryLogin(); return;
} }
case 'fetchClues': { case 'fetchClues': {
this.fetchClues(); await this.fetchClues();
break; return;
}
} }
}); }
} }
async tryLogin() { async tryLogin() {
...@@ -82,10 +82,10 @@ class EasyPass { ...@@ -82,10 +82,10 @@ class EasyPass {
if (loginSuccess) { if (loginSuccess) {
return true; return true;
} else { } else {
throw new errors.TryLoginError(`尝试登录异常: ${e}`); throw new errors.TryLoginError('尝试登录失败');
} }
} catch (e) { } catch (e) {
throw e; throw new errors.TryLoginError(`尝试登录异常: ${e}`);
} }
} }
...@@ -237,36 +237,41 @@ class EasyPass { ...@@ -237,36 +237,41 @@ class EasyPass {
$('#dataTable #grvNewCarOpportunity tr').not('.th').each(function(i, elem) { $('#dataTable #grvNewCarOpportunity tr').not('.th').each(function(i, elem) {
const clue = {}; const clue = {};
// const area, created;
// 主体信息样本:赵永亮[河南新乡],电话15249705814,订购大迈X5升级版 1.5T 手动 精英型2017款 // 主体信息样本:赵永亮[河南新乡],电话15249705814,订购大迈X5升级版 1.5T 手动 精英型2017款
const ptitleStr = $(this).find('.msg p').attr('title').trim() || ''; const ptitleStr = ($(this).find('.msg p').attr('title') || '').trim();
const ptitleStrArr = ptitleStr.split(',') || []; const ptitlePieces = ptitleStr.split(',') || [];
const customerNameAreaStr = ptitleStrArr[0].trim() || ''; const customerNameAreaStr = (ptitlePieces[0] || '').trim();
const customerPhoneStr = ptitleStrArr[1].trim() || '';
const customerExpectCarStr = ptitleStrArr[2].trim() || ''; const nameAreaMatch = customerNameAreaStr.match(/(.*?)\[(.*?)\]/);
clue.customerName = (nameAreaMatch[1] || '').trim();
const customerNameAreaMatch = customerNameAreaStr.match(/(.*?)\[(.*?)\]/); clue.customerArea = clue.licenseArea = (nameAreaMatch[2] || '').trim();
clue.customerName = customerNameAreaMatch[1].trim() || ''; clue.customerPhone = (ptitlePieces[1] || '').replace('电话', '').trim();
clue.customerArea = customerNameAreaMatch[2].trim() || ''; clue.expectCar = (ptitlePieces[2] || '').replace('订购', '').trim();
clue.customerPhone = customerPhoneStr.replace('电话', '').trim();
clue.customerExpectCar = customerExpectCarStr.replace('订购', '').trim();
// 提交时间样本:提交时间:2017-08-10 08:31 // 提交时间样本:提交时间:2017-08-10 08:31
const customerCreatedTimeStr = $(this).find('.msg p a span:contains(提交时间)').text(); const customerCreatedAtStr = $(this).find('.msg p a span:contains(提交时间)').text() || '';
clue.customerCreatedTime = customerCreatedTimeStr.replace('提交时间:', '').trim(); clue.createdAt = customerCreatedAtStr.replace('提交时间:', '').trim();
clue.SalesName = $(this).find('td span[title]').text().trim(); clue.salesName = $(this).find('td span[title]').text().trim();
clues.push(clue); clues.push(clue);
console.log('客户序号:', clues.length); console.log('客户序号:', clues.length);
console.log('客户姓名:', clue.customerName); console.log('客户姓名:', clue.customerName);
console.log('上牌地区:', clue.customerArea);
console.log('客户号码:', clue.customerPhone); console.log('客户号码:', clue.customerPhone);
console.log('负责销售:', clue.SalesName); console.log('上牌地区:', clue.customerArea);
console.log('线索获得时间:', clue.customerCreatedTime); console.log('负责销售:', clue.salesName);
console.log('线索获得时间:', clue.createdAt);
console.log('线索意向车型:', clue.customerExpectCar); console.log('线索意向车型:', clue.customerExpectCar);
console.log('==========================================================================='); console.log('===========================================================================');
}); });
if (this.params.userid) {
await DealerHelper.saveClues({
clues: clues,
userid: this.params.userid,
webname: this.params.webname
});
}
// 判断是否最后一页有两种情况:1.只有一页时分页按钮不存在 2.末页按钮置灰 // 判断是否最后一页有两种情况:1.只有一页时分页按钮不存在 2.末页按钮置灰
const isLastPage = !$('#pager1').length || $('#pager1 a:contains(末页)').prop('disabled'); const isLastPage = !$('#pager1').length || $('#pager1 a:contains(末页)').prop('disabled');
if (!isLastPage) { if (!isLastPage) {
......
...@@ -32,7 +32,7 @@ class Spider { ...@@ -32,7 +32,7 @@ class Spider {
} }
} }
execute() { async execute() {
this.spider.execute(); this.spider.execute();
} }
} }
......
...@@ -8,61 +8,64 @@ const moment = require('moment'); ...@@ -8,61 +8,64 @@ const moment = require('moment');
const day = moment().subtract(3, 'days').format('YYYY.MM.DD'); const day = moment().subtract(3, 'days').format('YYYY.MM.DD');
const axios = require('axios'); const axios = require('axios');
// console.log(moment().subtract(30, 'days').format('YYYY.MM.DD'));
// return;
// const cookie = require('cookie'); // const cookie = require('cookie');
// console.log(cookie.serialize('foo', 'bar')); // console.log(cookie.serialize('foo', 'bar'));
// return; // return;
const getCookies = async () => { // const getCookies = async () => {
const client = await redis.createClient(); // const client = await redis.createClient();
const cookies_key = 'autohome_cookies'; // const cookies_key = 'autohome_cookies';
let cookies = JSON.parse(await client.getAsync(cookies_key)); // let cookies = JSON.parse(await client.getAsync(cookies_key));
let a = []; // let a = [];
await cookies.forEach((c) => { // await cookies.forEach((c) => {
c.expires = (new Date()).getTime() + (1000 * 60 * 60); // c.expires = (new Date()).getTime() + (1000 * 60 * 60);
a.push(`${c.name}=${c.value}`); // a.push(`${c.name}=${c.value}`);
// for (let [k, v] of Object.entries(c)) { // // for (let [k, v] of Object.entries(c)) {
// a.push(`${k}=${v}`); // // a.push(`${k}=${v}`);
// } // // }
}); // });
a = a.join(';'); // a = a.join(';');
// console.log(a); // // console.log(a);
// return; // // return;
await client.quit(); // await client.quit();
//
let url = 'http://ics.autohome.com.cn/Dms/Order/SearchOrderList'; // let url = 'http://ics.autohome.com.cn/Dms/Order/SearchOrderList';
url = 'http://ics.autohome.com.cn/passport/Home/Index'; // url = 'http://ics.autohome.com.cn/passport/Home/Index';
// url = 'https://www.zhihu.com/'; // // url = 'https://www.zhihu.com/';
//
axios.get(url, { // axios.get(url, {
withCredentials: true, // withCredentials: true,
headers:{ // headers:{
Cookie: a // Cookie: a
} // }
}).then(res => { // }).then(res => {
console.log(JSON.stringify(res.data)); // console.log(JSON.stringify(res.data));
const writeStream = fs.createWriteStream('test2.html'); // const writeStream = fs.createWriteStream('test2.html');
writeStream.write(JSON.stringify(res.data)); // writeStream.write(JSON.stringify(res.data));
}); // });
return; // return;
//
got(url, { // got(url, {
headers: { // headers: {
'Cookie': a // 'Cookie': a
} // }
}).then(response => { // }).then(response => {
// response.body = ''; // // response.body = '';
// console.log(response); // // console.log(response);
const writeStream = fs.createWriteStream('test2.html'); // const writeStream = fs.createWriteStream('test2.html');
writeStream.write(JSON.stringify(response.body)); // writeStream.write(JSON.stringify(response.body));
}); // });
} // }
getCookies(); // getCookies();
return; // return;
let info = 'showCusDetailWithId("302761")'; // let info = 'showCusDetailWithId("302761")';
var m = info.match(/showCusDetailWithId\("(\d*)"\)/); // var m = info.match(/showCusDetailWithId\("(\d*)"\)/);
console.log(m); // console.log(m);
return; // return;
// class AppError extends Error { // class AppError extends Error {
...@@ -160,8 +163,6 @@ const testHorseman = async () => { ...@@ -160,8 +163,6 @@ const testHorseman = async () => {
// }) // })
.close(); .close();
} }
testHorseman();
return;
async function test (l) { async function test (l) {
await Promise.delay(l*1000).then(async function() { await Promise.delay(l*1000).then(async function() {
...@@ -173,11 +174,11 @@ async function test (l) { ...@@ -173,11 +174,11 @@ async function test (l) {
(async () => { (async () => {
console.log((new Date()).toDateString()); console.log((new Date()).toDateString());
const global_var = '全局变量'; // const global_var = '全局变量';
const test_fun = () => { // const test_fun = () => {
console.log(global_var); // console.log(global_var);
} // }
test_fun(); // test_fun();
let list = [1, 2, 3, 4, 5]; let list = [1, 2, 3, 4, 5];
for (l of list) { for (l of list) {
console.log((new Date()).toLocaleString()); console.log((new Date()).toLocaleString());
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment