Commit ee696005 by 马玮

Fetch clues into testing database

parent 19e1740d
......@@ -25,7 +25,16 @@ sudo yum install redis
- [x] 功能:捕获程序错误及异常
- [x] 功能:线索入库
- [x] 功能:验证码解析完毕删除
- [ ] 功能:线索入库前对数据进行基础校验,所有字段入库前检查去空格(50%)
- [x] 功能:打码工具余额不足邮件报警
- [x] 功能:登录增加每天尝试登录限制,超过10次不再登录,防止第三方改版导致验证码浪费
- [x] 功能:代理随机切换
- [ ] 功能:登录错误细分(密码错误、验证码错误等区分处理入库)
- [x] 功能:线索车型映射
- [ ] 功能:线索顾客映射
- [ ] 功能:线索销售映射(不一定做)
- [ ] 功能:生成账号记录命令行工具
- [ ] 功能:发现第三方车型和本地不匹配将未知车型入库方便开发爬取同步车型
- [ ] 功能:线索入库前对数据进行基础校验(如车型不匹配等如何处理)
- [ ] 功能:Cluster分布式进程调度
- [ ] 功能:增加日志系统
- [ ] 功能:增加随机userAgent
......
......@@ -8,24 +8,40 @@ const program = require('commander');
const config = require('config');
const captcha = require('./lib/captcha');
const Spider = require('./lib/spider');
const poolCluster = require('./lib/database/poolCluster');
const DealerHelper = require('./lib/helpers/Dealer');
program
.version('0.1.0')
.option('-u, --userid <user id>', 'Assign our user id')
.option('-t, --task <task name>', 'Add task we want to execute')
.option('-w, --webname <website name>', 'Add website we want fetch')
.option('-T, --thirdpartyAccountID <thirdparty account ID>', 'Assign thirdparty account ID')
.parse(process.argv);
const commandError = [];
if (!program.thirdpartyAccountID) {
commandError.push('缺少thirdpartyAccountID!');
}
if (!program.task) {
commandError.push('缺少task!');
}
if (commandError.length > 0) {
console.log(commandError.join(': '));
program.outputHelp();
process.exit(1);
}
// console.log(process.pid);
poolCluster.getConnection('master', (err, connection) => {
const dealerWebInfo = config.get(program.webname);
const spider = new Spider({
userid : program.userid,
task : program.task,
webname : program.webname,
username : dealerWebInfo.username,
password : dealerWebInfo.password
(async () => {
const account = await DealerHelper.getAccount({
thirdpartyAccountID: program.thirdpartyAccountID
});
// new Buffer('hnmz147852.').toString('base64')
// new Buffer('Q2hlY2hlbmcyMzUj', 'base64').toString();
const params = Object.assign({
task: program.task,
thirdpartyAccountID: program.thirdpartyAccountID,
}, account);
const spider = new Spider(params);
spider.execute();
});
\ No newline at end of file
})();
\ No newline at end of file
......@@ -5,20 +5,20 @@ host = 'http://api.dama2.com:7766/app/'
user = 'test'
pwd = 'test'
[dealer.autoifeng]
[autoifeng]
username = '上海车城汽车'
password = 'Checheng235#'
captcha_type = 'four_characters'
captchaType = 'FOUR_CHARACTERS'
[dealer.easypass]
[easypass]
username = '100074110'
password = 'hnmz147852.'
captcha_type = 'arithmetic'
captchaType = 'ARITHMETIC'
[dealer.autohome]
[autohome]
username = '河南明志汽车大迈8054'
password = 'hnmz147852.'
captcha_type = 'four_letters'
captchaType = 'FOUR_LETTERS'
[captcha.ruokuai]
username = 'chedev'
......@@ -27,13 +27,26 @@ softid = 86134
softkey = 'b167ed636a224990a2f04ae2d28d1542'
[captcha.ruokuai.typeids]
four_letters = 2040 # 四个英文字母
four_characters = 3040 # 四个字母数字混合
arithmetic = 7100 # 算术题
FOUR_LETTERS = 2040 # 四个英文字母
FOUR_CHARACTERS = 3040 # 四个字母数字混合
ARITHMETIC = 7100 # 算术题
[db.master]
host = 'localhost'
[DB.NODES.MASTER_CRM]
host = 'rm-bp10h7b832629p429o.mysql.rds.aliyuncs.com'
port = 3306
user = 'root'
password = 'root'
database = 'test'
user = 'car_base'
password = 'car_base2046'
database = 'car_crm'
connectionLimit = 500
[DB.NODES.MASTER_CAR]
host = 'rm-bp10h7b832629p429o.mysql.rds.aliyuncs.com'
port = 3306
user = 'car_base'
password = 'car_base2046'
database = 'car_new_test'
connectionLimit = 500
[CLUE_INPUT_TYPE]
autohome = 18
easypass = 21
[DB.NODES.MASTER_CRM]
host = 'rm-bp10h7b832629p429o.mysql.rds.aliyuncs.com'
port = 3306
user = 'car_base'
password = 'car_base2046'
database = 'car_crm'
connectionLimit = 500
[DB.NODES.MASTER_CAR]
host = 'rm-bp10h7b832629p429o.mysql.rds.aliyuncs.com'
port = 3306
user = 'car_base'
password = 'car_base2046'
database = 'car_new_test'
connectionLimit = 500
\ No newline at end of file
const config = require('config');
const poolCluster = require('./database/poolCluster');
// 自定义模块
class DI {
constructor(params) {
this.params = params;
}
static async getConnection(nodeID) {
return new Promise(function(resolve, reject) {
poolCluster.getConnection(nodeID, function (err, connection) {
if (err) {
reject(err);
} else {
resolve(connection);
}
});
});
}
}
module.exports = DI;
\ No newline at end of file
// process.env.NODE_CONFIG_DIR = '../../config';
const config = require('config');
const mysql = require('mysql2');
const mysql = require('mysql');
const clusterConfig = {
removeNodeErrorCount: 5,
defaultSelector: 'RR'
};
const poolCluster = mysql.createPoolCluster(clusterConfig);
const db = config.get('db');
const nodes = config.get('DB.NODES');
for (let [nodeId, nodeConfig] of Object.entries(db)) {
for (let [nodeID, nodeConfig] of Object.entries(nodes)) {
console.log(nodeConfig);
poolCluster.add(nodeId, nodeConfig);
poolCluster.add(nodeID, nodeConfig);
}
module.exports = poolCluster;
......@@ -42,46 +42,51 @@ class Autohome {
}
async tryLogin() {
try {
let newCookies;
let oldCookies = await DealerHelper.getCookies(this.params);
let loginSuccess = false;
if (oldCookies) {
console.log('oldCookies:', JSON.stringify(oldCookies));
const horseman = new Horseman({
ignoreSSLErrors: true
});
return new Promise(async (resolve, reject) => {
try {
let newCookies;
let oldCookies = await DealerHelper.getCookies(this.params);
let loginSuccess = false;
if (oldCookies) {
console.log('oldCookies:', JSON.stringify(oldCookies));
const horseman = new Horseman({
ignoreSSLErrors: true
});
loginSuccess =
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.cookies(oldCookies)
.open('http://ics.Autohome.com.cn/passport/Home/Index')
.screenshot('try.png')
.exists('#loginout');
newCookies = await horseman.cookies();
await horseman.close();
}
loginSuccess =
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.cookies(oldCookies)
.open('http://ics.Autohome.com.cn/passport/Home/Index')
.screenshot('try.png')
.exists('#loginout');
newCookies = await horseman.cookies();
await horseman.close();
}
if (loginSuccess) {
const params = this.params;
params.cookies = newCookies;
console.log('newCookies:', JSON.stringify(newCookies));
await DealerHelper.saveCookies(params);
if (loginSuccess) {
const params = this.params;
params.cookies = newCookies;
console.log('newCookies:', JSON.stringify(newCookies));
await DealerHelper.saveCookies(params);
if (this.params.task === 'tryLogin') {
console.log('尝试登陆成功');
resolve(true);
} else {
if (this.params.task === 'tryLogin') {
console.log('尝试登录失败');
return;
} else {
reject(new errors.TryLoginError('尝试登录失败'));
}
}
return true;
} else {
throw new errors.TryLoginError('尝试登录失败');
} catch (e) {
reject(new errors.TryLoginError(`尝试登录异常: ${e}`));
}
} catch (e) {
throw new errors.TryLoginError(`尝试登录异常: ${e}`);
}
});
}
async login() {
......@@ -103,6 +108,8 @@ class Autohome {
const username = this.params.username;
const password = this.params.password;
console.log('用户名:', username);
console.log('密码:', password);
const horseman = new Horseman({
ignoreSSLErrors: true
......@@ -130,7 +137,7 @@ class Autohome {
// 验证码解码
let captchaText;
try {
const captchaType = config.get(this.params.webname)['captcha_type'];
const captchaType = config.get(this.params.webname)['captchaType'];
captchaText = await captcha.decodeBase64(captchaType, base64Text);
console.info('captchaText:', captchaText);
} catch (e) {
......@@ -151,13 +158,14 @@ class Autohome {
await
horseman
.click('[id="btnDealer"]')
.waitForNextPage({ timeout: 5000 })
.wait(2000)
.waitForNextPage({ timeout: 10000 })
.screenshot('m3.png')
.exists('#loginout');
if (loginSuccess) {
console.log('登录成功!');
const cookies = await horseman .cookies();
const cookies = await horseman.cookies();
const params = this.params;
params.cookies = cookies;
console.log(JSON.stringify(cookies));
......@@ -203,7 +211,7 @@ class Autohome {
params.provinceId = -2;
params.cityId = -2;
params.status = -1;
params.startTime = moment().subtract(3, 'days').format('YYYY.MM.DD');
params.startTime = moment().subtract(90, 'days').format('YYYY.MM.DD');
params.endtime = moment().format('YYYY.MM.DD');
params.pageIndex = 1
params.pageSize = 20;
......@@ -235,7 +243,7 @@ class Autohome {
const clues = [];
for (let l of clueData.result.list) {
const clue = {};
customerIndex++;
customerIndex += 1;
// 名字字符串样本:<a href='#' onclick='showCusDetailWithId("303590")'>田华</a><br/><span></span>
const idMatch = l.CustomerNameStr.match(/showCusDetailWithId\("(\d+)"\)/) || [];
// 手机地区字符串样本:13253979998<br/>河南 三门峡
......@@ -253,7 +261,7 @@ class Autohome {
clue.orderType = l.OrderTypeStr.trim();
clue.orderState = l.OrderStateStr.trim();
clue.licenseArea = l.LicenseCityStr.trim();
clue.expectCar = l.SpecNameStr.trim();
clue.intentionDes = l.SpecNameStr.trim();
clue.createdAt = l.LeadTimeStr.trim();
clues.push(clue);
......@@ -266,7 +274,7 @@ class Autohome {
console.log('销售号码:', clue.salesPhone);
console.log('线索获得时间:', clue.createdAt);
console.log('上牌地区:', clue.licenseArea);
console.log('线索意向车型:', clue.expectCar);
console.log('线索意向车型:', clue.intentionDes);
// TODO: just for debug, remove them later
console.log('线索类型:', clue.orderType);
......@@ -274,20 +282,20 @@ class Autohome {
console.log('===========================================================================');
}
if (this.params.userid) {
if (this.params.dealerID) {
await DealerHelper.saveClues({
clues: clues,
userid: this.params.userid,
dealerID: this.params.dealerID,
webname: this.params.webname
});
}
// 判断是否抓取完全
if (customerIndex < rowcount) {
let randomSecs = randomInt(1, 8);
let randomSecs = randomInt(1, 2);
console.log(`随机等待${randomSecs}秒`);
await Promise.delay(randomSecs*1000).then(async function() {
params.pageIndex++;
params.pageIndex += 1;
await fetchByPage();
});
}
......
......@@ -127,7 +127,7 @@ class Easypass {
// 验证码解码
let captchaText;
try {
const captchaType = config.get(this.params.webname)['captcha_type'];
const captchaType = config.get(this.params.webname)['captchaType'];
captchaText = await captcha.decodeBase64(captchaType, base64Text);
console.info('captchaText:', captchaText);
} catch (e) {
......@@ -196,7 +196,7 @@ class Easypass {
console.log('networkRequest', networkRequest);
});
const txtBeginTime = moment().subtract(9, 'days').format('YYYY-MM-DD');
const txtBeginTime = moment().subtract(90, 'days').format('YYYY-MM-DD');
await
horseman
......@@ -227,9 +227,10 @@ class Easypass {
const nameAreaMatch = customerNameAreaStr.match(/(.*?)\[(.*?)\]/);
clue.customerName = (nameAreaMatch[1] || '').trim();
clue.customerArea = clue.licenseArea = (nameAreaMatch[2] || '').trim();
clue.licenseArea = (nameAreaMatch[2] || '').trim();
clue.customerArea = clue.licenseArea;
clue.customerPhone = (ptitlePieces[1] || '').replace('电话', '').trim();
clue.expectCar = (ptitlePieces[2] || '').replace('订购', '').trim();
clue.intentionDes = (ptitlePieces[2] || '').replace('订购', '').trim();
// 提交时间样本:提交时间:2017-08-10 08:31
const customerCreatedAtStr = $(this).find('.msg p a span:contains(提交时间)').text() || '';
......@@ -242,15 +243,15 @@ class Easypass {
console.log('客户号码:', clue.customerPhone);
console.log('上牌地区:', clue.customerArea);
console.log('负责销售:', clue.salesName);
console.log('线索意向车型:', clue.expectCar);
console.log('线索意向车型:', clue.intentionDes);
console.log('线索获得时间:', clue.createdAt);
console.log('===========================================================================');
});
if (this.params.userid) {
if (this.params.dealerID) {
await DealerHelper.saveClues({
clues: clues,
userid: this.params.userid,
dealerID: this.params.dealerID,
webname: this.params.webname
});
}
......@@ -266,7 +267,7 @@ class Easypass {
.waitForSelector('#UpdatePanel1')
.screenshot('list3.png');
let randomSecs = randomInt(1, 5);
let randomSecs = randomInt(1, 2);
console.log(`随机等待${randomSecs}秒`);
await Promise.delay(randomSecs*1000).then(async function() {
await fetchByPage();
......
......@@ -4,23 +4,22 @@ const dealer = require('./dealer');
class Spider {
constructor(params) {
let self = this;
let _params = {};
this.params = Object.assign(_params, params);
this.params = Object.assign({}, params);
this.spider = this.getSpider();
}
getSpider() {
let spider;
switch (this.params.webname) {
case 'dealer.autoifeng': {
spider = new dealer.AutoIfeng(this.params);
case 'autoifeng': {
spider = new dealer.Autoifeng(this.params);
break;
}
case 'dealer.autohome': {
case 'autohome': {
spider = new dealer.Autohome(this.params);
break;
}
case 'dealer.easypass': {
case 'easypass': {
spider = new dealer.Easypass(this.params);
break;
}
......
UPDATE `crm_dd_input_type` SET `name`='易车' WHERE (`id`='21')
ALTER TABLE `crm_clue`
ADD INDEX `customer_car` (`shop_id`, `clue_input_type`, `customer_phone`, `intention_des`, `create_time`) ;
\ No newline at end of file
......@@ -7,9 +7,41 @@ const fs = require('fs');
const moment = require('moment');
const day = moment().subtract(3, 'days').format('YYYY.MM.DD');
const axios = require('axios');
const config = require('config');
console.log(moment('2017-08-09 09:56').format('X'));
return;
console.log(config.get('clueInputType')['dealer.autohome']);
return;
// best
// import { es6 } from './AirbnbStyleGuide';
// export default es6;
// // good
// // filename es6.js
// import { es6 } from './AirbnbStyleGuide';
// export default es6;
// // good
// import foo, { named1, named2 } from 'foo';
//
// // good
// import foo, {
// named1,
// named2,
// } from 'foo';
//
// // good
// export default function foo() {}
// use args, use toString in class
(function () {
console.log('Welcome to the Internet. Please follow me.');
}());
console.log(moment().add(1, 'days').toString());
console.log(moment().toString());
throw '1';
return;
console.log(fs.existsSync('/tmp/a') && fs.statSync('/tmp/a').isFile());
......
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