Commit 9e607d02 by 马玮

Add missing files

parent 002c411a
'use strict';
process.env.NODE_CONFIG_DIR = '../config';
const Promise = require('bluebird');
const fs = require('fs');
const redis = require('redis');
const config = require('config');
const cheerio = require('cheerio');
const Horseman = require('node-horseman');
const moment = require('moment');
var randomInt = require('random-int');
const axios = require('axios');
// 自定义模块
const captcha = require('../../captcha');
const errors = require('../../errors');
const DealerHelper = require('../../helpers/Dealer');
Promise.promisifyAll(redis);
Promise.promisifyAll(fs);
axios.defaults.withCredentials = true;
class Autohome {
constructor(params) {
this.params = params;
}
async execute() {
switch (this.params.task) {
case 'login': {
await this.login();
return;
}
case 'tryLogin': {
await this.tryLogin();
return;
}
case 'fetchClues': {
await this.fetchClues();
return;
}
}
}
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
});
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 (this.params.task === 'tryLogin') {
console.log('尝试登陆成功');
}
return true;
} else {
throw new errors.TryLoginError('尝试登录失败');
}
} catch (e) {
throw new errors.TryLoginError(`尝试登录异常: ${e}`);
}
}
async login() {
try {
let loginSuccess;
try {
loginSuccess = await this.tryLogin();
} catch (e) {
console.log(e.message);
}
if (loginSuccess) {
console.log('尝试登录成功');
return;
} else {
console.log('尝试登录失败');
}
console.log('开始表单登录');
const username = this.params.username;
const password = this.params.password;
const horseman = new Horseman({
ignoreSSLErrors: true
});
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.open('http://ics.Autohome.com.cn/passport/');
horseman.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
console.log('networkRequest', networkRequest);
});
// 验证码存储到磁盘
const base64Text =
await
horseman
.screenshot('m1.png')
.crop('#imgValidCodeDealer', 'captcha1.png')
.cropBase64('#imgValidCodeDealer', 'PNG');
// 验证码解码
let captchaText;
try {
const captchaType = config.get(this.params.webname)['captcha_type'];
captchaText = await captcha.decodeBase64(captchaType, base64Text);
console.info('captchaText:', captchaText);
} catch (e) {
console.log(e.toString());
return;
}
// 填写登录表单
await
horseman
.type('input[id="UserNameDealer"]', username)
.type('input[id="PasswordDealer"]', password)
.type('input[id="checkCodeDealer"]', captchaText)
.screenshot('m2.png');
// 提交登录表单
loginSuccess =
await
horseman
.click('[id="btnDealer"]')
.waitForNextPage({ timeout: 5000 })
.screenshot('m3.png')
.exists('#loginout');
if (loginSuccess) {
console.log('登录成功!');
const cookies = await horseman .cookies();
const params = this.params;
params.cookies = cookies;
console.log(JSON.stringify(cookies));
await DealerHelper.saveCookies(params);
}
await horseman.close();
if (loginSuccess) {
return true;
} else {
throw new errors.LoginError('登录失败');
}
} catch (e) {
throw new errors.LoginError(`登录异常: ${e}`);
}
}
// 抓取线索
async fetchClues() {
try {
try {
await this.login();
console.log('登录成功');
} catch (e) {
console.log(e.message);
// 登录失败更新数据库cookie状态
return;
}
const headerCookie = await DealerHelper.getHeaderCookie(this.params);
let rowcount;
let customerIndex = 0;
const params = {};
params.appid = 'dms';
params.orderType = 1;
params.priPub = -1;
params.factoryId = 0;
params.seriesId = 0;
params.specId = 0;
params.areaType = 0;
params.provinceId = -2;
params.cityId = -2;
params.status = -1;
params.startTime = moment().subtract(3, 'days').format('YYYY.MM.DD');
params.endtime = moment().format('YYYY.MM.DD');
params.pageIndex = 1
params.pageSize = 20;
params.salesid = 0;
params.dealerId = 0;
params.productId = 0;
params.assignDealerId = 0;
const fetchByPage = async () => {
if (!rowcount) {
console.log(`线索日期: ${params.startTime} - ${params.endtime}`);
}
console.log(`线索页面: ${params.pageIndex}`);
axios.get('http://ics.Autohome.com.cn/Dms/Order/SearchOrderList', {
params: params,
headers:{
Cookie: headerCookie
}
}).then(async res => {
const clueData = res.data;
const writeStream = fs.createWriteStream('res.html');
writeStream.write(JSON.stringify(res.data));
if (!rowcount) {
rowcount = clueData.result.rowcount;
console.log('只进入一次总数:', rowcount);
}
const clues = [];
for (let l of clueData.result.list) {
const clue = {};
customerIndex++;
// 名字字符串样本:<a href='#' onclick='showCusDetailWithId("303590")'>田华</a><br/><span></span>
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);
console.log('客户序号:', customerIndex);
console.log('客户ID:', clue.customerId);
console.log('客户姓名:', clue.customerName);
console.log('客户号码:', clue.customerPhone);
console.log('客户地区:', clue.customerArea);
console.log('负责销售:', clue.salesName);
console.log('销售号码:', clue.salesPhone);
console.log('线索获得时间:', clue.createdAt);
console.log('上牌地区:', clue.licenseArea);
console.log('线索意向车型:', clue.expectCar);
// TODO: just for debug, remove them later
console.log('线索类型:', clue.orderType);
console.log('线索状态:', clue.orderState);
console.log('===========================================================================');
}
if (this.params.userid) {
await DealerHelper.saveClues({
clues: clues,
userid: this.params.userid,
webname: this.params.webname
});
}
// 判断是否抓取完全
if (customerIndex < rowcount) {
let randomSecs = randomInt(1, 8);
console.log(`随机等待${randomSecs}秒`);
await Promise.delay(randomSecs*1000).then(async function() {
params.pageIndex++;
await fetchByPage();
});
}
});
}
await fetchByPage();
return;
} catch (e) {
console.dir(e.stack);
// throw e;
}
}
}
module.exports = Autohome;
\ No newline at end of file
'use strict';
const phantom = require('phantom');
const cheerio = require('cheerio');
class AutoIfeng {
constructor(params) {
this.params = params;
console.log(params);
}
execute() {
return new Promise((resolve, reject) => {
switch (this.params.task) {
case 'login': {
console.log('do login');
this.login();
break;
}
case 'tryLogin': {
break;
}
}
});
}
async login() {
const passport = this.params.username;
const password = this.params.password;
const instance = await phantom.create(['--ignore-ssl-errors=yes']);
const page = await instance.createPage();
page.property('viewportSize', {width: 1920, height: 1080});
await page.on("onResourceRequested", function(requestData) {
console.info('Requesting', requestData.url)
});
const status = await page.open('http://dealer.auto.ifeng.com/dealerback/dealerIndexPage');
console.log(status);
console.log(passport);
page.evaluate(function(passport, password) {
document.querySelector('input[id=passport]').value = passport;
document.querySelector('input[id=password]').value = password;
}).then(function(html) {
console.log(html);
});
const content = await page.property('content');
const $ = cheerio.load(content)
console.log('倒霉');
await page.render('m2.png');
await instance.exit();
}
}
module.exports = AutoIfeng;
\ No newline at end of file
'use strict';
process.env.NODE_CONFIG_DIR = '../config';
const Promise = require('bluebird');
const fs = require('fs');
const redis = require('redis');
const config = require('config');
const cheerio = require('cheerio');
const Horseman = require('node-horseman');
const moment = require('moment');
var randomInt = require('random-int');
const axios = require('axios');
// 自定义模块
const captcha = require('../../captcha');
const errors = require('../../errors');
const DealerHelper = require('../../helpers/Dealer');
Promise.promisifyAll(redis);
Promise.promisifyAll(fs);
axios.defaults.withCredentials = true;
class Easypass {
constructor(params) {
this.params = params;
}
async execute() {
switch (this.params.task) {
case 'login': {
await this.login();
return;
}
case 'tryLogin': {
await this.tryLogin();
return;
}
case 'fetchClues': {
await this.fetchClues();
return;
}
}
}
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
});
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://dealer.Easypass.cn/HomeIndex.aspx')
.screenshot('try.png')
.exists('#myAccountLi');
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 (this.params.task === 'tryLogin') {
console.log('尝试登陆成功');
}
return true;
} else {
throw new errors.TryLoginError('尝试登录失败');
}
} catch (e) {
throw new errors.TryLoginError(`尝试登录异常: ${e}`);
}
}
async login() {
try {
let loginSuccess;
try {
loginSuccess = await this.tryLogin();
} catch (e) {
console.log(e.message);
}
if (loginSuccess) {
console.log('尝试登录成功');
return;
} else {
console.log('尝试登录失败');
}
console.log('开始表单登录');
const username = this.params.username;
const password = this.params.password;
const horseman = new Horseman({
ignoreSSLErrors: true
});
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.open('http://dealer.Easypass.cn/LoginPage/DefaultLogin.aspx')
.screenshot('m1.png');
console.log('打开了登录页');
// 验证码存储到磁盘
const base64Text =
await
horseman
.crop('#imgVerificationCode', 'captcha1.png')
.cropBase64('#imgVerificationCode', 'PNG');
console.log('验证码准备完毕');
// 验证码解码
let captchaText;
try {
const captchaType = config.get(this.params.webname)['captcha_type'];
captchaText = await captcha.decodeBase64(captchaType, base64Text);
console.info('captchaText:', captchaText);
} catch (e) {
console.log(e.toString());
return;
}
// 填写登录表单
await
horseman
.type('input[id="txtUserName"]', username)
.type('input[id="txtPwd"]', password)
.type('input[id="txtVerificationCode"]', captchaText)
.screenshot('m2.png');
// 提交登录表单
loginSuccess =
await
horseman
.click('[id="btnLogin"]')
.screenshot('m2.5.png')
.waitForNextPage({ timeout: 5000 })
.screenshot('m3.png')
.exists('#myAccountLi');
if (loginSuccess) {
console.log('登录成功!');
const cookies = await horseman .cookies();
const params = this.params;
params.cookies = cookies;
console.log(JSON.stringify(cookies));
await DealerHelper.saveCookies(params);
}
await horseman.close();
if (loginSuccess) {
return true;
} else {
throw new errors.LoginError('登录失败');
}
} catch (e) {
throw new errors.LoginError(`登录异常: ${e}`);
}
}
// 抓取线索
async fetchClues() {
try {
try {
await this.login();
console.log('登录成功');
} catch (e) {
console.log(e.message);
// 登录失败更新数据库cookie状态
return;
}
const cookies = await DealerHelper.getCookies(this.params);
if (cookies) {
const horseman = new Horseman({
ignoreSSLErrors: true
});
horseman.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
console.log('networkRequest', networkRequest);
});
const txtBeginTime = moment().subtract(9, 'days').format('YYYY-MM-DD');
await
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.cookies(cookies)
.open('http://app.Easypass.cn/lmsnew/OutmodedDefault.aspx')
.waitForSelector('#UpdatePanel1')
.waitForSelector('#pager1')
.type('input[id="txtBeginTime"]', txtBeginTime)
.click('input[id="btnSearch"]')
.wait(1000)
// .waitForNextPage()
.screenshot('list.png');
// TODO: if waitfor failed need some error check
let clues = [];
const fetchByPage = async () => {
const html = await horseman.html('#UpdatePanel1');
const $ = cheerio.load(html);
$('#dataTable #grvNewCarOpportunity tr').not('.th').each(function(i, elem) {
const clue = {};
// 主体信息样本:赵永亮[河南新乡],电话15249705814,订购大迈X5升级版 1.5T 手动 精英型2017款
const ptitleStr = ($(this).find('.msg p').attr('title') || '').trim();
const ptitlePieces = ptitleStr.split(',') || [];
const customerNameAreaStr = (ptitlePieces[0] || '').trim();
const nameAreaMatch = customerNameAreaStr.match(/(.*?)\[(.*?)\]/);
clue.customerName = (nameAreaMatch[1] || '').trim();
clue.customerArea = clue.licenseArea = (nameAreaMatch[2] || '').trim();
clue.customerPhone = (ptitlePieces[1] || '').replace('电话', '').trim();
clue.expectCar = (ptitlePieces[2] || '').replace('订购', '').trim();
// 提交时间样本:提交时间:2017-08-10 08:31
const customerCreatedAtStr = $(this).find('.msg p a span:contains(提交时间)').text() || '';
clue.createdAt = customerCreatedAtStr.replace('提交时间:', '').trim();
clue.salesName = $(this).find('td span[title]').text().trim();
clues.push(clue);
console.log('客户序号:', clues.length);
console.log('客户姓名:', clue.customerName);
console.log('客户号码:', clue.customerPhone);
console.log('上牌地区:', clue.customerArea);
console.log('负责销售:', clue.salesName);
console.log('线索意向车型:', clue.expectCar);
console.log('线索获得时间:', clue.createdAt);
console.log('===========================================================================');
});
if (this.params.userid) {
await DealerHelper.saveClues({
clues: clues,
userid: this.params.userid,
webname: this.params.webname
});
}
// 判断是否最后一页有两种情况:1.只有一页时分页按钮不存在 2.末页按钮置灰
const isLastPage = !$('#pager1').length || $('#pager1 a:contains(末页)').prop('disabled');
if (!isLastPage) {
await horseman
.click('a.paginator:contains(下一页)')
.screenshot('list2.png')
// .waitForNextPage()
.wait(1000)
.waitForSelector('#UpdatePanel1')
.screenshot('list3.png');
let randomSecs = randomInt(1, 5);
console.log(`随机等待${randomSecs}秒`);
await Promise.delay(randomSecs*1000).then(async function() {
await fetchByPage();
});
}
}
await fetchByPage();
await horseman.close();
return;
} else {
throw new Error('no cookie');
}
} catch (e) {
throw e;
}
}
}
module.exports = Easypass;
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